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


Bookmark this link on del.icio.us (saved by 0 users)

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

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 2010 All Rights Reserved DevCurry.com by Suprotim Agarwal