Book Image

jQuery for Designers Beginner's Guide Second Edition

By : Natalie Maclees
Book Image

jQuery for Designers Beginner's Guide Second Edition

By: Natalie Maclees

Overview of this book

Table of Contents (21 chapters)
jQuery for Designers Beginner's Guide Second Edition
Credits
About the Author
Acknowledgments
About the Reviewers
www.PacktPub.com
Preface
Index

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.

  1. Open up your empty scripts.js file and add a document ready statement, as follows:

    $(document).ready(function(){
      // Our code goes here
    });
  2. 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 a radio button. Let's add a filter to...