Sunday, April 17, 2011

How to set a javascript variable or reuse one from another function

I have a problem going on here and without going into a lot of detail and confusing everyone, let me just ask the simple question.

Here are two functions. I need to use the "id" variable in the SubmitForm() function as well. Can someone please tell me how to do this? This is how new I am to js. :)

Thanks for the help.

  AC.chooseFunc = function(id,label)
  {
    document.qSearch.action = ".index.php?dc=2&id="+ id;
    //document.qSearch.action = "index.php?dc=2";
    document.qSearch.submit();
  }

  *** This one fails.
  function SubmitForm(id)
  {
    document.qSearch.action = "index.php?dc=2&id="+ id;
    document.qSearch.submit()
  }

What I need is the "id" var appended to the query string in the SubmitForm Function. Can someone tell me how to do this please? Thanks for the help!


Can this not be done??

From stackoverflow
  • Could you not just use a hidden input and have PHP add it to the query string?

  • i dont know if you would want to do this, but you could make the variable global in other words declare it outside of both functions.

    Samuel : just put idGlobal = "" outside of both functions. then you set the var in the function, idGlobal = id, it will store it to the variable that has already been declared. Then in the other function just use idGlobal in place of id. Also look at SidneySM's post on this page to see what im talking about.
  • Is id null? Check the value of id...

    alert(id);
    

    The second function looks OK to me. The problem could be your passing null into it.

    Aaron Daniels : I think it goes to show that there is nothing wrong with the function, but rather, something wrong in how you are calling the function. More code is needed to help.
  • it's pretty clear that the two functions aren't being called in the same way.

    As mentioned in another comment, alert the value to see what you're really getting in the function. The function itself looks fine, so the only conclusion is that they are not working from the same data OR they are called in different ways.

    I'd recommend posting a little more of the code in the call tree

  • First, as a disclaimer, I think we would all be able to give you better answers if you post an example page demonstrating how the document is put together.

    Here's one way you can make it work. At or near the top of your script (or <script> tag) declare a variable:

    var storedId;
    

    Then, at the top of AC.chooseFunc, copy the value of id to storedId:

      AC.chooseFunc = function(id,label)
      {
        storedId = id;
        ...
    

    Finally, remove id from SubmitForm's parameters and use storedId instead:

      function SubmitForm()
      {
        document.qSearch.action = "index.php?dc=2&id="+ storedId;
        document.qSearch.submit();
      }
    

0 comments:

Post a Comment