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.
See Derek's answer, which should now be the accepted answer. It includes everything this answer had included and more.
(I tried to delete this answer after Derek updated his to include library examples, but with the green checkmark, SO won't let me)
This is the simplest way you can have your own javascript function be called when an
onSubmit
occurs.HTML
JavaScript
Based on your requirements you can also do the following without libraries like jQuery:
Add this to your head:
And your form may still look something like:
With jQuery:
Why do people always use jQuery when it isn't necessary?
Why can't people just use simple JavaScript?
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,Listening to the
submit
event with librariesIf 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:
jQuery
Where
ele
is the form element reference, andcallback
being the callback function reference. ReferenceAngularJS (1.x)
Very straightforward, where
$scope
is the scope provided by the framework inside your controller. ReferenceReact
Simply pass in a handler to the
onSubmit
prop. ReferenceOther 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.
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/