Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 920
Owl Avatar asked Jul 05 '17 02:07

Owl


People also ask

Why submit button is not working?

Sometimes the problem is caused by old versions of the Javascript files, cached by your browser and can be fixed by clearing the browser cache. You can use the browser console of your browser for debugging. After the Javascript error is fixed, the submit button will automatically be enabled.

What event triggers when a form is submitted?

The submit event triggers when the form is submitted, it is usually used to validate the form before sending it to the server or to abort the submission and process it in JavaScript. The method form. submit() allows to initiate form sending from JavaScript.

Why form submit is not working in jquery?

The NUMBER ONE error is having ANYTHING with the reserved word submit as ID or NAME in your form. If you plan to call . submit() on the form AND the form has submit as id or name on any form element, then you need to rename that form element, since the form's submit method/handler is shadowed by the name/id attribute.


1 Answers

According to MDN:

The form's onsubmit event handler (for example, onsubmit="return false;") will not be triggered when invoking this method from Gecko-based applications. In general, it is not guaranteed to be invoked by HTML user agents.

To get around this issue, try using dispatchEvent():

var form = document.querySelector('form');

form.addEventListener('submit', function () {
  console.log('invoked');
  
  return false;
});

// form.submit();
form.dispatchEvent(new Event('submit'));
<form></form>
like image 74
Patrick Roberts Avatar answered Oct 07 '22 05:10

Patrick Roberts