Should jQuery's $(form).submit(); not trigger onSubmit within the form tag?
Asked Answered
P

9

44

I have the following:

<script type="text/javascript">
function CancelFormButton(button) {
    $(button.form).submit();
}
</script>

<form onsubmit="alert('here');">
<input type="button" value="Cancel" onClick="CancelFormButton(this);" />
</form>

When I click the "Cancel" button, the onsubmit from the form tag is not triggered.

This line instead submits the form successfully: $(button.form).submit(); but skips the alert('here'); within the onsubmit in the form tag.

Is this correct or am I doing something wrong?

By the way, in this case, I want this functionality, but I'm just wondering if I'm going to run into a problem in a browser where the onsubmit is triggered.

Pastorship answered 14/3, 2009 at 6:51 Comment(1)
W
59

Sorry, misunderstood your question.

According to Javascript - capturing onsubmit when calling form.submit():

I was recently asked: "Why doesn't the form.onsubmit event get fired when I submit my form using javascript?"

The answer: Current browsers do not adhere to this part of the html specification. The event only fires when it is activated by a user - and does not fire when activated by code.

(emphasis added).

Note: "activated by a user" also includes hitting submit buttons (probably including default submit behaviour from the enter key but I haven't tried this). Nor, I believe, does it get triggered if you (with code) click a submit button.

Whack answered 14/3, 2009 at 6:52 Comment(9)
This still does not trigger the onsubmit of the form... is this normal?Pastorship
Yes, this.form is valid and correct and works in all browsers. #418576 Also, you didn't answer the question.Pastorship
Also, confused by "specifically there is know form attribute on button."Pastorship
Grrr, answer again instead of changing the question! I look like a fool now :( But, thxs for the explanation. I wonder what "current" is.Pastorship
Just tested in IE6 and it too doesn't trigger the onsubmit...so it's been a while.Pastorship
Yes, it is triggered with enter and clicking a submit button. And yes, it is not triggered when using code to click a submit button.Pastorship
the link doesn't seem to exist anymore?Midland
Wondering, if this is still the same?Orgiastic
try to .submit() after doing an asynchronous form validation and you'll find out why onSubmit isn't triggered. (do you like endless loops?) I need to validate files haven't change on AWS S3, which means the old validate which returned 'true' on valid must default to returning 'false' and then fork the remote check which uses .submit() if successful to submit the form.Bitt
S
34

This work around will fix the issue found by @Cletus.

function submitForm(form) {
    //get the form element's document to create the input control with
    //(this way will work across windows in IE8)
    var button = form.ownerDocument.createElement('input');
    //make sure it can't be seen/disrupts layout (even momentarily)
    button.style.display = 'none';
    //make it such that it will invoke submit if clicked
    button.type = 'submit';
    //append it and click it
    form.appendChild(button).click();
    //if it was prevented, make sure we don't get a build up of buttons
    form.removeChild(button);
}

Will work on all modern browsers.
Will work across tabs/spawned child windows (yes, even in IE<9).
And is in vanilla!

Just pass it a DOM reference to a form element and it'll make sure all the attached listeners, the onsubmit, and (if its not prevented by then) finally, submit the form.

St answered 6/8, 2013 at 5:14 Comment(7)
Just put this into my MVC web app's Scripts folder. Working great!! I use this where I have JQuery UI dialog buttons trying to submit forms that are being displayed from within the child IFRAME.Rhinoplasty
I try different solutions, only this one works on all browsers, and trigger submit event and check form validity (display errors messages) dabblet.com/gist/97a733d9c787dcf99cffChilpancingo
And here's the jquery equivalent if you are already using jQuery: var form = $('youFormSelector'); var submitBtn = $('<input type="submit"></input>'); submitBtn.appendTo(form); submitBtn.click(); submitBtn.remove();Sextodecimo
@FrankFajardo, you're assuming a few things here. That if form is in a different document, appendTo() will clone the element for you (I used open() to make a popup and tried appendTo(); didn't work). That jQuery's click() will invoke submit (I tested it on an anchor and the page didn't change). However, even if you're right you can make it much more succinct than you did, otherwise you might as well just continue to use my code. function submitForm(form) { $('<input>', {type:'submit', style:'display:none'}).appendTo(form).click().remove(); }St
Thanks for the comment @Hashbrown. I'm not quite sure why you say I assume that jQuery's click() will invoke submit. It is the input's type attribute, as far as I understand from your original code, that submits the form. My code seems to work with a form on the same document (which is the context of this SO). Also, I do not quite get your comment on cloning. Isn't $('<input/>').appendTo(target) same as creating first $('<input/>') and then appending it to the target?Sextodecimo
No worries. I meant that jQuery's click(), at least for me, doesn't seem to invoke the element's click. It seems to only fire the attached click events. So <a>s won't relocate, <input type="submit">s wont submit, et cetera. And the other point was that the jQuery code we wrote will work for all forms but those that exist in documents out side the runtime. Id est, in frames and child windows. For jQuery you'd need to adopt first in those cases. The magic in my original script is form.ownerDocument, creating the element in the native environment from the get-goSt
@Hashbrown, jQuery's click() definitely works for me. I must say I have not tested it on elements within frames or other documents. But I consider that as outside of scope of this SO item. Besides, I do not think there is a 'one size fits all' solution for that.Sextodecimo
C
8

I suppose it's reasonable to want this behavior in some cases, but I would argue that code not triggering a form submission should (always) be the default behavior. Suppose you want to catch a form's submission with

$("form").submit(function(e){
    e.preventDefault();
});

and then do some validation on the input. If code could trigger submit handlers, you could never include

$("form").submit()

inside this handler because it would result in an infinite loop (the SAME handler would be called, prevent the submission, validate, and resubmit). You need to be able to manually submit a form inside a submit handler without triggering the same handler.

I realize this doesn't ANSWER the question directly, but there are lots of other answers on this page about how this functionality can be hacked, and I felt that this needed to be pointed out (and it's too long for a comment).

Corset answered 9/5, 2013 at 11:48 Comment(0)
M
6

My simple solution:

$("form").children('input[type="submit"]').click();

It is work for me.

Milksop answered 28/10, 2009 at 14:45 Comment(2)
That is assuming you have submit buttomPate
If you have a submit button, then the onsubmit would be firing. I believe the issue is when type=button onclick=...Rubato
H
2

trigger('submit') does not work.beacuse onSubmit method does not get fired. the following code works for me, call onSubmit method when using this code :

$("form").find(':submit').click();

Heyde answered 16/9, 2017 at 11:35 Comment(0)
B
1

Try to trigger() event in your function:

$("form").trigger('submit'); // and then... do submit()
Bombshell answered 14/3, 2009 at 7:34 Comment(2)
Nope, also does not trigger the submit.Pastorship
$("form").trigger("submit") is the same as $("form").submit(). The second is just a shortcut.Corset
J
1

Instead of

$("form").submit()

try this

 $("<input type='submit' id='btn_tmpSubmit'/>").css('display','none').appendTo('form');
 $("#btn_tmpSubmit").click();
Jim answered 12/8, 2015 at 9:2 Comment(0)
C
0

I found this question serval years ago.

recently I tried to "rewrite" the submit method. below is my code

window.onload= function (){
for(var i= 0;i<document.forms.length;i++){
    (function (p){
        var form= document.forms[i];
        var originFn= form.submit;
        form.submit=function (){
            //do something you like
            alert("submitting "+form.id+" using submit method !");
            originFn();
        }
        form.onsubmit= function (){
            alert("submitting "+form.id+" with onsubmit event !");
        }
    })(i);


}

}

<form method="get" action="" id="form1">
<input type="submit" value="提交form1" />
<input type="button" name="" id="" value="button模拟提交1" onclick="document.forms[0].submit();" /></form>

It did in IE,but failed in other browsers for the same reason as "cletus"

Cobol answered 31/5, 2009 at 3:21 Comment(0)
E
0

The easiest solution to workaround this is to create 'temporary' input with type submit and trigger click:

var submitInput = $("<input type='submit' />");
$("#aspnetForm").append(submitInput);
submitInput.trigger("click");
Earwig answered 5/9, 2012 at 9:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.