189

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.

3
  • 11
    Why not document.forms['yourForm'].onsubmit = function(){}? Or addEventListener? Sep 14, 2011 at 0: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, 2011 at 0:45
  • see this answer 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 ) Feb 4, 2022 at 2:43

5 Answers 5

616

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/

13
  • 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, 2011 at 0: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, 2011 at 1:00
  • 6
    I personally believe that a person should first knows the basics. Sep 14, 2011 at 2: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. Jul 8, 2016 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, 2016 at 22:43
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();
}
3
  • 3
    Why did you decide to bind the 'submitted' function? There's no use of 'this' in the function.
    – Lior
    Jun 7, 2017 at 21:06
  • bind is indeed unnecessary.
    – pstadler
    Apr 7, 2020 at 6:36
  • After binding it worked for me without the preventDefault wouldn't work Oct 24, 2022 at 13:07
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>
1
  • 17
    always use addEventListener instead of onsubmit or onload to allow other developers to add their own listeners. Jul 15, 2017 at 9: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

-1

With jQuery:

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

    if (pass)
        return true;
    else
        return false;
});
0

Not the answer you're looking for? Browse other questions tagged or ask your own question.