Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trigger form submission with javascript

Tags:

javascript

I have a form that I would like to submit via JavaScript. Obviously this can be achieved by:

document.getElementById("myForm").submit();

The issue is that I have a listener on the submit event that looks like this:

document.getElementById("myForm").addEventListener("submit", function(event) {
    event.preventDefault();
    // Other work
});

This event handler is not triggered when I call .submit(). From 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.

So, given this restraint, how can I submit the form in a way that ensures the event handler is invoked?

like image 347
Max Avatar asked Feb 02 '16 13:02

Max


People also ask

How can you submit a form using JavaScript?

In javascript onclick event , you can use form. submit() method to submit form. You can perform submit action by, submit button, by clicking on hyperlink, button and image tag etc. You can also perform javascript form submission by form attributes like id, name, class, tag name as well.

How do you trigger a form submit from a button?

You can tie a submit button to a form that the button doesn't live inside of. The trick is to give the form an id and then reference that id with the button's form property. With this setup, clicking the Submit button will cause the form to be submitted.

What happens on form submit JavaScript?

The submit event fires when the user clicks a submit button ( <button> or <input type="submit">) or presses Enter while editing a field (e.g. <input type="text">) in a form. The event is not sent to the form when calling the form. submit() method directly.


1 Answers

You need create a submit event, then dispatch it.

(function () {
              if ( typeof window.CustomEvent === "function" ) return false;

              function CustomEvent ( event, params ) {
                params = params || { bubbles: true, cancelable: true, detail: undefined };
                var evt = document.createEvent('submit');
                evt.initCustomEvent( event, params.bubbles, params.cancelable, params.detail );
                return evt;
               }

              CustomEvent.prototype = window.Event.prototype;

              window.CustomEvent = CustomEvent;

})();
var evt = new CustomEvent("submit", {"bubbles":true, "cancelable": true});
document.getElementById("myForm").addEventListener("submit",function(event) {
                event.preventDefault();
                alert('submit');
});

Then when you want submit this function you need to call:

!document.getElementById("myForm").dispatchEvent(evt);

For more event info see dispatchEvent.

like image 200
Raymond Cheng Avatar answered Sep 18 '22 15:09

Raymond Cheng