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.
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.
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.
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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With