Reputation: 6172
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.
Upvotes: 7
Views: 37531
Reputation: 38046
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.
Upvotes: 8
Reputation: 39704
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>
Upvotes: 7