O'Reilly logo

jQuery and JavaScript Phrasebook by Brad Dayley

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Forcing Focus to and Away from Form Elements

$("input[type=radio]").on("change",   function(){     $("#cardNum").focus(); });

A great flow control feature in web forms is to automatically focus elements when you know the user is ready to enter them. For example, if the user selects a year and the next element is a month selection, it makes sense to make the month active for the user automatically.

To set the focus of an element in jQuery, call the .focus() method on that object. For example, the following code sets the focus for an object with id="nextInput":

$("#nextInput").focus();

You can also blur an element that you want to navigate the user away from by calling the .blur() method:

$("#nextInput").blur(); ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required