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:
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>
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
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
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/
document.forms['yourForm'].onsubmit = function(){}
? OraddEventListener
? – Scriptorium... using ( document.forms )
– Bestial