Events
First things first, let's memorize the events you'll most often work with:
change
change of an element's value
submit
form submission
When will these come in handy? It's simple — tracking change lets you handle events like changes to <select>, <input type="radio">, and others. You'll need this for dynamically modifying a form or validating an entered value.
Tracking submit is necessary for validating that all form fields are filled in correctly, as well as for submitting the form via AJAX.
Let's start with the latter. First, let's take a simple form:
<form action="index.html">
<input type="text" name="firstname" value="Ivan"/>
<input type="text" name="lastname" value="Ivanov"/>
<input type="submit"/>
</form>And try to submit it to the address from the "action" attribute via an AJAX request (to track the submit event, you can use the shorthand method of the same name):
$("form").submit(function(){
// for code readability
let $form = $(this);
// you get what I'm talking about here, right?
// this is one of the forms of an AJAX request
$.post(
$form.attr("action"), // the URL to send data to
$form.serialize() // form data
);
// disable the default action
return false;
});There's one unfamiliar method that snuck in here — serialize(), it's responsible for "collecting" form data in a format convenient for transmission:
There's also a serializeArray() method — it presents the collected data as an array of objects:
Even though this chapter is about events, we can't go further without methods — meet the method we'll need quite often:
val()
get the value of the first form element in the selection
val(value)
set the value for all form elements in the selection
Now, with its help, we can add some validation to the previous code:
Good, we can now work with the form, all that's left is to hook up a more reasonable error output (yes, using alert() is frowned upon):
When resubmitting the form, don't forget to clear the messages left from the previous validation:
Now we can combine the code snippets and get the following version:
The previous example has already been added to the form.basic.html page — try submitting the form; you can examine the resulting request and response in the browser console:
I wanted to come back to the list of form events and mention the missing ones:
focus
focus on an element; there's also a shorthand method focus() for working with this event; you'll need it if you want to show a hint for a form element on focus
blur
focus left the element + the blur() method; useful for validating the form as fields are being filled in
select
text selection in "textarea" and "input[type=text]" + the select() method; if you ever set out to build your own WYSIWYG, you'll get to know this one really well
Examples of tracking all form events are available on the form.events.html page:
Last updated