Time for action — setting focus to the first field

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.

  1. Open up your empty scripts.js file and add a document ready statement.
    $(document).ready(function(){
    //code goes here
    });
    
  2. 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'),
    });
    
  3. 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.

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.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.126.241