Why won't form.submit() trigger the "submit" event?

Viewed 10936

I am submitting my form by using JavaScript .submit() function.

form.submit();

But when I using addEventListener to capture my submit event, it wouldn't work.

form.addEventListener("submit", function(event){
    //codes
});

I found out addEvenetListener function will only listen for onsubmit event instead of submit. Is there have any alternative solution to call my function when form.submit() is executed?

ps: For some reasons I need to stay with form.submit() to submit my form instead of using submit button.

5 Answers

Instead of using this and then adding event listener to the submit

var form = $('form');
form.submit();
form.addEventListener("submit", function(event){
    //codes
});

You could use this instead

var form = $('form');
form.submit(function(event){
    // Do something on submit
});

If you need not to support IE & Safari, you can use requestSubmit().

Unlike @Patrick Roberts's solution of dispatchEvent(), this will also validate form's content! As per MDN:

submit() submits the form, but that's all it does. requestSubmit(), on the other hand, acts as if a submit button were clicked. The form's content is validated, and the form is submitted only if validation succeeds. Once the form has been submitted, the submit event is sent back to the form object.

Alternatively, if you have access to the submit button (which I'm aware of that OP hasn't), btn.click() is the best supported way since it will do form validation as well as will trigger submit event.

Related