Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make on submit form in Javascript

I have tried to search it but no favorable results found.

I don't use JQuery and I want to make it with pure JavaScript. I want to make the same as <form onsubmit="somefunction();"> but directly from JavaScript.

Something like:

if(document.getElementById("myid").ISSUBMIT) {
    somefunction();
}

in Jquery I can make it with on.submit, but how to do in JavaScript? Thanks a lot!

like image 690
MM PP Avatar asked Dec 15 '22 20:12

MM PP


1 Answers

You get a reference to the form element, and then either:

  1. Assign a function to onsubmit

    theFormElement.onsubmit = function() { /* ... */ };
    

    or

  2. Use addEventListener / attachEvent to hook the submit event. If you don't need IE8 support, you can just use addEventListener:

    theFormElement.addEventListener("submit", function(e) {
        // your code here
    }, false);
    

    If you also need IE8 support, you probably want to use a function that handles the fact that IE8 uses attachEvent instead of addEventListener, such as the one in this answer.

To get a reference to the form, you can use an id on the form and use document.getElementById, or (on any modern browser, and even IE8) you can use document.querySelector and any CSS selector that will find the form.

like image 74
T.J. Crowder Avatar answered Jan 01 '23 05:01

T.J. Crowder