$(function() { $('input[id$=tbDate]').datepicker() });
What we are going discuss in this article is how to switch focus to another input box or element after selecting a date from the Datepicker.
Your web page may have many fields that your users need to fill before submission. At times, it can be time consuming if the page has many fields. One-way we can make this quick, is by switching fields automatically once values in fields are selected or typed.
Typically, a user selects a date by clicking the calendar associated with the Datepicker. Using a jQuery function, we will attach an input box with the Datepicker widget.
The Datepicker will display itself when focus is set on the input box, with which the Datepicker in attached. After we select a date from the Datepicker, it will automatically switch or shift focus on another control or element.
The jQuery UI Datepicker comes with many useful and easy to implement functions also called Widgets, which has proved to be a boon for web developers. Functions like, Date Formatting, Animating and Displaying Multiple Months are widely used by developers, throughout the world.
jQuery .onClose() Function
I our example here, we will use the jQuery onClose() function. This function is actually called when the Datepicker is closed, irrespective of any value (date) is selected. The method takes 2 parameters, i.e. the date as dateText and the instance inst of the Datepicker. While executing this function, we want to switch focus to another input box or control.
Here we have two input boxes, one is tied with the Datepicker function and the other is to set the focus on.
<html> <head> <title>jQuery Datepicker Example</title> <link href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/themes/base/jquery-ui.css" rel="stylesheet" /> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/jquery-ui.min.js"></script> </head> <body> <p> Click on the first field, select a date and it will automatically change focus to the next textbox. </p> <div> <p>Date: <input type="text" id="tbDate" /></p> <p>Name: <input type="text" id="tbToSetFocus" /></p> </div> </body> <script> $(document).ready(function() { $('input[id$=tbDate]').datepicker({ onClose: function(dateText, inst) { $("#tbToSetFocus").focus(); } }); }); </script> </html>
There not much to say about this feature. All you have to do is add an Input element to your web page and attach it with the datePicker() method inside the <script> section. You are ready to use it. I’ll share more useful articles and code snippets about jQuery Datepicker widget in my blog later.