Reputation: 2854
In jQuery-Mobile I'm submitting a form programmatically and I want to capture the submit event to perform some validations before. I have already tried the following solution provided in other questions about jQuery:
$(document).ready(function(){
$('#my_form').bind('submit', function() {
alert('before submit');
...
});
});
But I cannot get the function executed and the alert displayed. Does anyone know any other way to achieve this?
My form is something like:
<form id="my_form" method="POST" action="..." data-theme="b">
And the way I am calling it programmatically, from another section of the same page is like this:
<input type="submit" onclick="document.forms['my_form'].submit(); return false;" value="Submit" data-theme="b"/>
Thank you in advance for your help.
Upvotes: 1
Views: 4404
Reputation: 177960
The submit handler of the form is NOT executed when you submit the form programatically.
NOTE: Do NOT use a submit button to programatically submit a form. Instead use button or allow the submission from the submit button to be handled, i.e.
<input type="button" onclick="document.forms['my_form'].submit()" value="Submit another form" data-theme="b"/>
(the above is not correct anyway since it needs the form to have a NAME, not just an ID)
So
<input type="button" onclick="document.forms['my_form_NAME'].submit()" value="Submit another form" data-theme="b"/>
OR
<input type="button" onclick="document.getElementById('my_form_ID').submit()" value="Submit another form" data-theme="b"/>
OR since you have jQuery:
<input type="button" onclick="$('#my_form_ID'].submit()" value="Submit another form" data-theme="b"/>
OR if you can put the button in the form (best way):
<input type="submit" value="Submit THIS form" data-theme="b"/>
But since you want to bind - here is how to submit using another button instead of the better way using the form's own submit button:
<form id="actualForm">...
.
.
</form>
<input type="button" id="subbut" value="Submit another form on this page" data-theme="b"/>
$(document).ready(function(){
$('#subbut').bind('click', function() {
alert('before submit');
...
$("#actualForm").submit();
});
});
If there is hardcoded inline behaviour you cannot change, use the jQuery to remove it too
How can I remove an inline onclick attribute with a bookmarklet?
$(document).ready(function(){
$('#subbut').attr('onclick',""); // or $('#subbut').onclick=null;
$('#subbut').bind('click', function() {
alert('before submit');
...
$("#actualForm").submit();
});
});
Upvotes: 4
Reputation: 118
Changing the return value of onClick to TRUE does the job:
<input type="submit" onclick="document.forms['my_form'].submit(); return ***true***;" vakue="Submit" data-theme="b"/>
Upvotes: -1