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.
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.
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.
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());
});
});
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);
}
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