The submit method in jQuery
Previously we used this construction:
$('form').on('submit', function(event) {
event.preventDefault();
});
Instead, we can also directly use the submit method in jQuery, which binds a form handler or executes an event:
$('form').submit(function(event) {
event.preventDefault();
});
In the following example, we have a simple form to which we will bind an event handler using the submit method, with a text field and a button - an input of type submit:
<p>jQuery</p>
<form action="/">
<div>
<input type="text">
<input type="submit">
</div>
</form>
<span></span>
Let's enter text into a text field, and when we click on a button, check this text. If we enter 'jQuery', then in the span we will show the text 'Good!', using the methods text and show, and if something else, then - 'Bad...':
$('form').submit(function(event) {
event.preventDefault();
if ($('input').first().val() === 'jQuery') {
$('span').text('Good!').show();
return;
}
$('span').text('Bad...').show();
});