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.
A JavaScript function can have any number of parameters. The 3 functions above were called with the same number of arguments as the number of parameters.
In JavaScript, we use the prompt() function to ask the user for input. As a parameter, we input the text we want to display to the user. Once the user presses “ok,” the input value is returned. We typically store user input in a variable so that we can use the information in our program.
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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With