185

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.

Carl0s1z
  • 4,683
  • 7
  • 32
  • 47
ed1t
  • 8,719
  • 17
  • 67
  • 110
  • 11
    Why not `document.forms['yourForm'].onsubmit = function(){}`? Or `addEventListener`? – Joseph Silber Sep 14 '11 at 00:39
  • 3
    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)? – nnnnnn Sep 14 '11 at 00:45
  • see this answer https://stackoverflow.com/a/70980807/14344959 for Pure JavaScript way for handle submit event for multiple forms in same page without using Id `... using ( document.forms )` – Harsh Patel Feb 04 '22 at 02:43

5 Answers5

612

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/

Derek 朕會功夫
  • 92,235
  • 44
  • 185
  • 247
  • 110
    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. – RobG Sep 14 '11 at 00:57
  • 50
    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. – RobG Sep 14 '11 at 01:00
  • 4
    @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. – RobG Sep 14 '11 at 01:11
  • 6
    I personally believe that a person should first knows the basics. – Derek 朕會功夫 Sep 14 '11 at 02:12
  • 10
    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. – Josh Sutterfield Jul 08 '16 at 20:52
  • 5
    If you need and already have jQuery in your project anyway, why not use it? otherwise, use JS – ProgZi Jul 17 '16 at 22:43
  • @ProgZi 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: https://jsperf.com/hc-selector-speed – Robin B Jun 01 '18 at 10:55
  • 1
    +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. – Ben Lee Aug 07 '18 at 16:41
  • @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`. – Derek 朕會功夫 Aug 09 '18 at 15:24
  • 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. – Lajos Arpad Sep 11 '19 at 03:11
  • 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? – Harshal Sharma Apr 02 '20 at 07:38
  • 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! – Gaurav Gupta May 07 '20 at 05:40
  • 1
    "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. – BevansDesign Aug 19 '20 at 19:57
16

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();
}
Derek Dawson
  • 502
  • 5
  • 14
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>
fakedob
  • 145
  • 3
  • 16
    always use `addEventListener` instead of onsubmit or onload to allow other developers to add their own listeners. – kuzey beytar Jul 15 '17 at 09:29
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

Harsh Patel
  • 1,032
  • 6
  • 21
-1

With jQuery:

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

    if (pass)
        return true;
    else
        return false;
});
Justin808
  • 20,859
  • 46
  • 160
  • 265