Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i use input fields as parameters to functions in javascript?

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.

like image 339
Michael Avatar asked Aug 19 '11 11:08

Michael


People also ask

Can JavaScript function accept parameters?

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.

How do you input a function in JavaScript?

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.


2 Answers

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.

like image 65
Sean Kinsey Avatar answered Oct 04 '22 00:10

Sean Kinsey


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>
like image 41
Mihai Iorga Avatar answered Oct 04 '22 01:10

Mihai Iorga