0

I have a variable var somewhere along my js program. lets call it 'tempVar'. I want to pass this variable when the button is being pushed. here is part of my code:

var TempVar=9;
<form id="boardButton" action="/test"  >
    <button id="joinBoardButton" >JOIN</button>
</form> 

how can I pass to the page test the content of Tempvar?

kakush
  • 3,334
  • 14
  • 47
  • 68
  • 3
    There are many things you can call Javascript variables. `var` is not one of them... – lonesomeday Jan 26 '12 at 20:52
  • ok so not 'var'... lets call it 'tempVar' I editted the question. 'test' is a file that does some kind of a calculation. – kakush Jan 26 '12 at 20:57
  • @lonesomeday actually, if you go `this['var'] = something` it will work, won't it? You'll just have to refer to it in the same way to pull out the variable. – Jeff Jan 26 '12 at 20:58
  • @Jeff: That's a property; not a variable. – pimvdb Jan 27 '12 at 08:59

4 Answers4

1

You can use the onclick attribute. Then once in JavaScript you can then seek out the values you need. If they are on the page already you can use document.getElementById(someID) to get the element, then grab your value that way.

You can also use the this keyword to access the DOM element just clicked. See : what's “this” in javascript onclick?

EDIT :

As for getting a variable you alreday had, if it has a large scope you can just access it directly.

Another way of doing this, is to save the value you want to re-use in a hidden input of your site and re-use when needed.

Hope this helps!

Community
  • 1
  • 1
blo0p3r
  • 6,790
  • 8
  • 49
  • 68
0

Assuming var is defined globally (on the window object):

<form id="boardButton" action="/test">
    <input type="hidden" name="var"/>
    <button id="joinBoardButton" onclick="this.form.elements['var'].value=window.var">JOIN</button>
</form> 
ori
  • 7,817
  • 1
  • 27
  • 31
0

You can add an input hidden value to your form

<input id="var" type='hidden' name='country' value=''>

Then you can set the value with onclick when you submit the form :

<button id="joinBoardButton" onclick="this.document.getElementById('var').value=var" >JOIN</button>
Kevin
  • 1,019
  • 10
  • 16
0

This should submit the form with the TempVar in the query string: .../test?TempVar=ABC

<script>
    var TempVar = "ABC";

    function setVar() {
        document.getElementById('TempVar').value=TempVar;
    }
</script>


<form id="boardButton" action="/test"  >
    <input type="hidden" id="TempVar" name="TempVar" value=""/>
    <input type="submit" id="joinBoardButton" value="JOIN" onclick="setVar();"/>
</form>
Gz Zheng
  • 311
  • 2
  • 7