How can I listen to the form submit event in javascript?
Asked Answered
M

5

190

I wanna write my own form validation javascript library and I've been looking on google how to detect if a submit button is clicked but all I found is code where you have to use onClick on onSubmit="function()" in html.

I would like to make this javascript so that I don't have to touch any html code like adding onSubmit or onClick javascript.

Myxomatosis answered 14/9, 2011 at 0:37 Comment(3)
Why not document.forms['yourForm'].onsubmit = function(){}? Or addEventListener?Scriptorium
Do you really want to check if the submit button was clicked, or do you want to check when the user submits the form (which they may do by clicking the button or by pressing Enter from one of the fields)?Stanwood
see this answer https://mcmap.net/q/82928/-how-can-i-listen-to-the-form-submit-event-in-javascript for Pure JavaScript way for handle submit event for multiple forms in same page without using Id ... using ( document.forms )Bestial
M
619

Why do people always use jQuery when it isn't necessary?
Why can't people just use simple JavaScript?

var ele = /*Your Form Element*/;
if(ele.addEventListener){
    ele.addEventListener("submit", callback, false);  //Modern browsers
}else if(ele.attachEvent){
    ele.attachEvent('onsubmit', callback);            //Old IE
}

callback is a function that you want to call when the form is being submitted.

About EventTarget.addEventListener, check out this documentation on MDN.

To cancel the native submit event (prevent the form from being submitted), use .preventDefault() in your callback function,

document.querySelector("#myForm").addEventListener("submit", function(e){
    if(!isValid){
        e.preventDefault();    //stop form from submitting
    }
});

Listening to the submit event with libraries

If for some reason that you've decided a library is necessary (you're already using one or you don't want to deal with cross-browser issues), here's a list of ways to listen to the submit event in common libraries:

  1. jQuery

    $(ele).submit(callback);
    

    Where ele is the form element reference, and callback being the callback function reference. Reference

    <iframe width="100%" height="100%" src="http://jsfiddle.net/DerekL/wnbo1hq0/show" frameborder="0"></iframe>
  1. AngularJS (1.x)

    <form ng-submit="callback()">
    
    $scope.callback = function(){ /*...*/ };
    

    Very straightforward, where $scope is the scope provided by the framework inside your controller. Reference

  2. React

    <form onSubmit={this.handleSubmit}>
    
    class YourComponent extends Component {
        // stuff
    
        handleSubmit(event) {
            // do whatever you need here
    
            // if you need to stop the submit event and 
            // perform/dispatch your own actions
            event.preventDefault();
        }
    
        // more stuff
    }
    

    Simply pass in a handler to the onSubmit prop. Reference

  3. Other frameworks/libraries

    Refer to the documentation of your framework.


Validation

You can always do your validation in JavaScript, but with HTML5 we also have native validation.

<!-- Must be a 5 digit number -->
<input type="number" required pattern="\d{5}">

You don't even need any JavaScript! Whenever native validation is not supported, you can fallback to a JavaScript validator.

Demo: http://jsfiddle.net/DerekL/L23wmo1L/

Matthus answered 14/9, 2011 at 0:47 Comment(14)
That 5 lines of "ghastly...ugly" code replaces the required functionality provided by 4,000 lines of jQuery, which must also be "ghastly...ugly" code too.Wooten
I don't have much against jQuery, only those who use it as a kind of magic incantation without realising that they can replace the entire thing with a few lines of code. Why not take the time to find out how browsers actually work? It's really not that hard.Wooten
@Ben - and just because you can do something with a library doesn't mean you should either, nor should others be dissuaded from learning the basics by replies of "just use library x". When someone asks a specific question about javascript, it's polite to answer the question using plain javascript. By all means suggest something from your library of choice, but answering the question should be the first priority.Wooten
I personally believe that a person should first knows the basics.Volny
in the same spirit, we really should try writing more assembly language. Half-joking (I quite prefer a jquery solution and think it's an endless rabbit hole if you really want to understand what's going on under the hood), but yes, I am glad that I DO know some assembly language, and know how the TCP connections are made, etc. I still wouldn't hand anyone a lower level solution just for the sake of teaching them the wonders of whats-under-the-hood.Tia
If you need and already have jQuery in your project anyway, why not use it? otherwise, use JSMousy
@Mousy ancient old discussion it seems (and this comment is from '16) but: performance. Here is a simple jsPerf test for just selectors. Using jQuery is 80% slower: jsperf.com/hc-selector-speedBiannual
+1 for including library examples. 7 years later I still think a library is a better general answer but given that your post now includes both library examples and vanilla javascript, I think this should be the accepted answer now. I tried to delete mine, but with the green checkmark, SO won't let me. So instead I've edited to make my answer a signpost to this one.Ankara
@BenLee A lot really has changed in these 7 years. We are building a lot more full scale web applications now and using popular frameworks are more common than ever. With that in mind, the native .addEventListener still has certain advantages but only in small pages where we wouldn't need a huge framework library - for example one shouldn't include the entire jQuery library just to use .submit.Volny
This answer deserves a big upvote. It is very helpful on the actual problem and it's also very very correct in saying "Why do people always use jQuery when it isn't necessary? Why can't people just use simple JavaScript?" I think the answer is that many programmers lack confidence in solving issues on their own. Instead, they use large libraries with lots of dependencies.Countersign
Is there a way to track all the forms from one page because I tried your method it is working only for getElementById i.e single form is there a way to do this using class?Logographic
in my case.. I wanted my form validation and 401 error code both to be working using xhr! "e.preventDefault()" worked for the same. Thank you!Penza
"Why do people always use jQuery when it isn't necessary?" Because other people don't necessarily have the same knowledge of coding that you do.Mavismavra
let's say you need to do that on multiple form, those 5 (already a bit ugly) lines of code start to become very ugly, jquery adds some readability to a problem which shouldn't be one if browsers provided good APISOutermost
S
17

This is the simplest way you can have your own javascript function be called when an onSubmit occurs.

HTML

<form>
    <input type="text" name="name">
    <input type="submit" name="submit">
</form>

JavaScript

window.onload = function() {
    var form = document.querySelector("form");
    form.onsubmit = submitted.bind(form);
}

function submitted(event) {
    event.preventDefault();
}
Soniferous answered 3/1, 2017 at 18:48 Comment(3)
Why did you decide to bind the 'submitted' function? There's no use of 'this' in the function.Etruria
bind is indeed unnecessary.Guth
After binding it worked for me without the preventDefault wouldn't workInflectional
R
4

Based on your requirements you can also do the following without libraries like jQuery:

Add this to your head:

window.onload = function () {
    document.getElementById("frmSubmit").onsubmit = function onSubmit(form) {
        var isValid = true;
        //validate your elems here
        isValid = false;

        if (!isValid) {
            alert("Please check your fields!");
            return false;
        }
        else {
            //you are good to go
            return true;
        }
    }
}

And your form may still look something like:

    <form id="frmSubmit" action="/Submit">
        <input type="submit" value="Submit" />
    </form>
Raynata answered 19/9, 2014 at 9:30 Comment(1)
always use addEventListener instead of onsubmit or onload to allow other developers to add their own listeners.Creaturely
B
2

If you have multiple forms in same page & you wants to handle submit event Listener without using Id

jQuery

$('form').submit(function (event) {
    targetObj = event.target;
    // do your logic
});

Pure JavaScript trick

Onload just do below way.

for(var i=0; i<document.forms.length; i++){
    var form = document.forms[i];
    form.addEventListener("submit", myListener,false);
}

credit :- Multiple Form Submit Event Listener Handling using JavaScript credit goes to Jan Pfeifer's Answer on StackOverflow Community

I hope this helps to someone

Bestial answered 4/2, 2022 at 2:37 Comment(0)
L
-1

With jQuery:

$('form').submit(function () {
    // Validate here

    if (pass)
        return true;
    else
        return false;
});
Longlived answered 14/9, 2011 at 0:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.