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(); ...

Get jQuery and JavaScript Phrasebook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.