We'll keep working with the sample form we set up in the last example. Here's how to set the focus to the first field in the form.
Open up your empty
scripts.js
file and add a document ready statement.$(document).ready(function(){ //code goes here });
Next up, we want to select the first field in our form. There are many different ways to go about that. In this case, I'm going to use the
id
of the first form element.$(document).ready(function(){ $('#username'); });
All that's left to do is call the
focus()
method for that element.$(document).ready(function(){ $('#username').focus(); });
Now if you refresh the page in the browser, you'll see that the cursor is blinking in the Username field of the form—the very first field.