Tom
Tom

Reputation:

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??

Upvotes: 1

Views: 4055

Answers (5)

s4y
s4y

Reputation: 51715

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();
  }

Upvotes: 3

Jonathan Fingland
Jonathan Fingland

Reputation: 57177

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

Upvotes: 0

Aaron Daniels
Aaron Daniels

Reputation: 9664

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.

Upvotes: 0

Samuel
Samuel

Reputation: 17171

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.

Upvotes: 1

Shane
Shane

Reputation: 851

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

Upvotes: 0

Related Questions