jQuery and ASP.NET

January 9, 2010

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



'Like' us on our FaceBook page if you find this blog useful. Thanks!


Did you like this post?
kick it on DotNetKicks.com Save on Delicious
subscribe via rss subscribe via e-mail
print this post follow me on twitter


About The Author

Suprotim Agarwal, ASP.NET Architecture MVP 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 has also written an EBook 51 Recipes using jQuery with ASP.NET Controls.

Follow him on twitter @suprotimagarwal

comments

1 Response to "jQuery UI DatePicker - Update two TextBoxes at the same time with the selected date"
  1. Joe Burt said...
    January 10, 2010 9:38 AM

    Fantastic! I never knew about the altfield option

 

Copyright © 2009-2011 All Rights Reserved for DevCurry.com by Suprotim Agarwal | Terms and Conditions