samedi 28 mars 2015

jQuery preventdefault submit form doesn't work when submitting form through js function?

I have this basic form:



<form id="myForm" name="myForm" action="index.php" method="post">
<input type="submit" value="Submit" />
</form>


Then my jQuery to attach submit event:



$( document ).ready(function() {
var frm = $('#myForm');
frm.submit(function (ev) {
ev.preventDefault();
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function (data) {
alert('ok');
}
});
});
});


When I press the submit button it works fine, I get the alert 'ok'.


But if I change the submit button to an actual button then add an onclick function through javascript, like this:



<input type="button" value="Submit" onclick="submitF(this.form);" />


JS:



function submitF(form) {
form.submit();
}


My jQuery event doesn't trigger, the form submits like it normally would.


If I'm attaching my jQuery function to the form submit event, why doesn't it trigger when javascript submits the form?


Aucun commentaire:

Enregistrer un commentaire