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.
scripts.js
file and add a document ready statement.$(document).ready(function(){ //code goes here });
id
of the first form element.$(document).ready(function(){
$('#username'),
});
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.
What just happened?
We used a couple of lines of jQuery to move focus to the first field in our form to make it easy for our site visitors to jump right into completing our form. It was as simple as selecting the first form element and then calling the focus()
method for that element.
18.118.126.241