Time for action – setting focus to the first field
We'll keep working with the sample form we set up in the previous example. Perform the following steps to set the focus to the first field in the form.
- Open up your empty
scripts.js
file and add a document ready statement, as follows:$(document).ready(function(){ // Our code goes here });
- Next up, we want to select the first field in our form. There are many different ways to go about this. While we could use the
id
attribute of the first field, this is not very flexible. If we update our form later to add a new field at the beginning, we'd also have to remember to update our JavaScript. Instead, let's just find the first input element, as follows:$(document).ready(function(){ $('input').first(); });
This works pretty well, but there are several cases where we would not like to set the focus on the first input element, for example, if the first element is disabled, or if it's a button, a checkbox, or...