Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass a form input value into a JavaScript function

I have a generic JavaScript function which takes one parameter

function foo(val) { ...} 

and I want to call the function when submit a form

<form>
<input type="text" id="formValueId"/>
<input type="button" onclick="foo(this.formValueId)"/>
</form>

but the expression foo(this.formValueId) does not work (not surprised, it was a desperate attempt), So the question is, how can I pass a form value to the javascript function. As I mentioned the javascript is generic and I don't want to manipulate the form inside it!

I could create a helper function in the middle to get the form values with jQuery (for example) and then call the function but I was wondering if I can do it without the helper function.

like image 501
nightograph Avatar asked Oct 10 '11 18:10

nightograph


People also ask

How do you pass user input 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.

How do you pass a value to a function in HTML?

Use the onclick attribute in a button tag with the function name and pass value in this function. With this method, you can also take input from users and pass parameters in the JavaScript function from HTML.


2 Answers

It might be cleaner to take out your inline click handler and do it like this:

$(document).ready(function() {
    $('#button-id').click(function() {
      foo($('#formValueId').val());
    });
});
like image 164
Clive Avatar answered Oct 18 '22 21:10

Clive


Give your inputs names it will make it easier

<form>
<input type="text" id="formValueId" name="valueId"/>
<input type="button" onclick="foo(this.form.valueId.value)"/>
</form>

UPDATE:

If you give your button an id things can be even easier:

<form>
<input type="text" id="formValueId" name="valueId"/>
<input type="button" id="theButton"/>
</form>

Javascript:

var button = document.getElementById("theButton"),
value =  button.form.valueId.value;
button.onclick = function() {
    foo(value);
}
like image 19
Ibu Avatar answered Oct 18 '22 20:10

Ibu