I have a generic JavaScript function which takes one parameter
function foo(val) { ...}
and I want to call the function when submit a form
Use onclick="foo(document.getElementById('formValueId').value)"
Well ya you can do that in this way.
<input type="text" name="address" id="address">
<div id="map_canvas" style="width: 500px; height: 300px"></div>
<input type="button" onclick="showAddress(address.value)" value="ShowMap"/>
Java Script
function showAddress(address){
alert("This is address :"+address)
}
That is one example for the same. and that will run.
There are several ways to approach this. Personally, I would avoid in-line scripting. Since you've tagged jQuery, let's use that.
HTML:
<form>
<input type="text" id="formValueId" name="valueId"/>
<input type="button" id="myButton" />
</form>
JavaScript:
$(document).ready(function() {
$('#myButton').click(function() {
foo($('#formValueId').val());
});
});
More stable approach:
<form onsubmit="foo($("#formValueId").val());return false;">
<input type="text" id="formValueId"/>
<input type="submit" value="Text on the button"/>
</form>
The return false;
is to prevent actual form submit (assuming you want that).
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);
}
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());
});
});