Submit and onclick not working together
<input type="submit" class="sub" onClick="exefunction2()" id="button">
When I click on the submit button onClick
is not working. How can I fix this? I need to work this on submitting the form because onClick
event contains values.
The best way is to call you method on the form tag like this:
<form onsubmit="return exefunction2();">
...
</form>
Returning false
will not submit the form, true
will submit!
to post more data (builded with exefunction2) you can use this
<script type="text/javascript">
function exefunction2(form) {
//add dynamic values
var dynValues = {
"val1": 1,
"val2": "bla"
};
for(var name in dynValues) {
//check if field exists
var input = null;
if(document.getElementsByName(name).length === 0) {
input = document.createElement('input');
input.setAttribute('name', name);
input.setAttribute('type', 'hidden');
form.appendChild(input);
}
else {
input = document.getElementsByName(name)[0];
}
input.setAttribute('value', dynValues[name]);
}
return true;
}
</script>
<form onsubmit="return exefunction2(this);">
<input type="submit" />
</form>
W3 schools has a good explanation here: http://www.w3schools.com/js/js_validation.asp
Basically, submit waits for a return value from onClick before doing anything. You can wire up a confirm() request too, if you like. If the form validates, just write something like return confirm("continue")
. It's an old question, but I hope it helps anyone who stumbles across it. Another big reason for failure is a bug in your script. Unfortunately, unless you are running a debugger in your browser, it is very difficult to know what if anything is crashing your script. Turning on your browser debugger can be helpful to trace any issues. In Chrome you can use CTRL-SHIFT-I for Windows or CMD-OPTION-I for Mac. If you pause on caught errors, you can find any syntax or fatal errors that are prematurely stopping your script.
You can submit the form with Javascript.
<form id="form_id" ...>
<input type="button" class="sub" onclick="exefunction2();" id="button">
The Javascript:
function exefunction2() {
...
document.forms["form_id"].submit();
}