Reputation: 17773
I had a piece of code that registered callbacks using jQuery on
(e.g. $(formElement).on('submit', callback)
) and somewhere in the application I was trying to trigger form submission using HTML Form element object (e.g. formElement.submit()
) without using jQuery. However, event handlers were not called, but when I simply changed code to $(formElement).submit()
, callbacks were called. So this is first question, why?
So I started to play around with different techniques of submitting / registering and this code works - callbacks were called ($formElement
is jQuery object with length of 1):
$formElement.on('submit', function () {
// do some stuff
});
$formElement.on('submit', function () {
// do more stuff
});
setTimeout(function() {
$formElement.submit();
}, 10000);
However changing it to :
setTimeout(function() {
$formElement[0].submit();
}, 10000);
Did not trigger callbacks. What is more, when I replaced $formElement.on
with $formElement[0].addEventListener
, callbacks were not called no matter how I trigger them (jQuery submit or HTML Form submit)
So probably I'm missing some fundamental knowledge about event handling. Could you help with that?
Upvotes: 0
Views: 812
Reputation: 144
I'm not very familiar with jquery but the .submit doesn't seem to actually submit the form but rather to register a listener to the submit event, whereas native .submit method on dom elements actually submits the form.
Here is a way to both listen to manual submission and to trigger a submission after 10 seconds:
const form = document.getElementById('someform');
form.addEventListener('submit', e => {
alert('form submitted');
});
setTimeout(() => {
form.dispatchEvent(new Event('submit'));
form.submit();
}, 10000);
I'm manually dispatching a submit event because the submit method seems to submit the form but not to trigger the event.
Upvotes: 1