jQuery UI DatePicker - Update two TextBoxes at the same time with the selected date

The jQuery UI DatePicker widget is very configurable and powerful, and I love using it whenever I can. I was recently working with the DatePicker widget and came across a requirement where two textboxes had to be updated at the same time with the selected date.

Assuming we have two textboxes called ‘date1’ and ‘date2’, to solve this requirement, developers would usually handle the ‘onSelect’ parameter of the datepicker to detect a change and update the second textbox as shown below:

<script type="text/javascript">
$(function() {
$("#date1").datepicker({
onSelect: function() {
$('#date2').val($('#date1').val());
}
});
});
</script>

However the configurable datepicker widget has an ‘altField’ option that allows us to specify a jQuery selector containing the id of the second textbox, making this requirement extremely simple to achieve. Here’s the code:

<html xmlns="http://www.w3.org/1999/xhtml">
<
head>
<
script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js">
</
script>
<
link rel="stylesheet" type="text/css" href="
http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/themes/base/jquery-ui.css
"/>
<
script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.min.js">
</
script>
<
title>Change value of One Calendar based on the value of the other</title>
</
head>
<
body>
<
label>Choose a date: </label>
<
input id="date1" />
<
br /><br />
<
label>Second date field: </label>
<
input id="date2" />
<
script type="text/javascript">
$(function() {
var dt = {
altField: "#date2"
};
$("#date1").datepicker(dt);
});
</script>
</
body>
</
html>

Here’s a Live Demo



Will you give this article a +1 ? Thanks in advance


About The Author

Suprotim Agarwal
Suprotim Agarwal, ASP.NET Architecture MVP (Microsoft Most Valuable Professional) works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He is the Editor of a Developer Magazine called DNC Magazine. He has also written two EBooks 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook

Follow him on twitter @suprotimagarwal

1 comment:

Joe Burt said...

Fantastic! I never knew about the altfield option