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
Tweet
1 comment:
Fantastic! I never knew about the altfield option
Post a Comment