Issue
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.
Solution
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>
Answered By - Patrick Roberts
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.