javascript - jQuery preventdefault submit form doesn't work when submitting form through js function? -
i have basic form:
<form id="myform" name="myform" action="index.php" method="post"> <input type="submit" value="submit" /> </form>
then jquery 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 press submit button works fine, alert 'ok'.
but if change submit button actual button add onclick function through javascript, this:
<input type="button" value="submit" onclick="submitf(this.form);" />
js:
function submitf(form) { form.submit(); }
my jquery event doesn't trigger, form submits would.
if i'm attaching jquery function form submit event, why doesn't trigger when javascript submits form?
it because jquery not prevent native submit trigger in javascript.
done form submit can prevented, , form can submitted programatically later, instance
$('form').on('submit', function(e) { e.preventdefault(): // stuff // submit form this.submit(); // not trigger event handler submits form instead });
if want trigger jquery event handler, , prevent form submit, do
function submitf(form) { $(form).submit(); }
Comments
Post a Comment