7

So I have some input text fields and a button

<input type=text value="a"/>
<input type=text value="b"/>
<input type=button onclick=???/>

and I want to use the values of those text fields as the parameters in a function that gets called when i click a button, say

function foo(a,b) {
    dostuff(a);
    dostuff(b);
}

I don't know what to put in the question marks. So what gets the value of the text inputs, I don't think document.getElementById gets the value of them, just the element itself.

Michael
  • 5,994
  • 7
  • 44
  • 56

2 Answers2

8

There are multiple ways to access those values, but the recommended one is to start by giving the input elements ID's.

<input type=text value="a" id="a"/>
<input type=text value="b" id="b"/>

Now, you can use document.getElementById to get the element, and then the value

<input type=button onclick="foo(document.getElementById('a').value,document.getElementById('b').value)" />

Note the use of ' vs " due to them being nested...

But you could also just pass the ID's to foo, and have foo do the getElementById-stuff.

Sean Kinsey
  • 37,689
  • 7
  • 52
  • 71
  • The framework was set to 'onLoad', so the `foo` function was captured in a closure and not available in the global scope. Set it to 'no wrap' and you should be good. – Sean Kinsey Aug 19 '11 at 11:39
  • Not all browsers (IE lte 4) support getElementById. See http://stackoverflow.com/a/1945802/2225787 – Agi Hammerthief Feb 22 '14 at 21:07
7

assign an id to inputs and then call them with getElementById

<input type="text" id="field1" value="a"/>
<input type="text" id="field2" value="b"/>
<input type=button onclick="foo('field1','field2');"/>

<script type="text/javascript">
    function foo(a,b) {
        elemA = document.getElementById(a).value;
        elemB = document.getElementById(b).value;
        dostuff(elemA);
        dostuff(elemB);
    }
</script>
Mihai Iorga
  • 39,330
  • 16
  • 106
  • 107