I have 2 sets of input boxes:
1) “Start Date I” and “End Date I”
2) “Start Date II” and “End Date II”
as it can be seen here: http://jsfiddle.net/YXzpj/
What I need is that whenever user sets the start and end dates of one side, chosen values should be copied to the other side.
For example:
User sets “Start Date I” and then “End Date I”, then the script should automatically copy both values to “Start Date II” and “End Date II”. If user changes any of the four fields, the form should update itself accordingly. In other words, these two sets of input boxes should mirror each other.
Here is my current code:
$(function() {
var currentTime = new Date();
$('#report2from1').attr('readonly','readonly');
$('#report2to1').attr('readonly','readonly');
var dates1 = $( "#report2from1, #report2to1" ).datepicker({
showButtonPanel: true,
changeMonth: true,
changeYear: true,
numberOfMonths: 1,
minDate: new Date(2010, 1 -1, 1),
maxDate: new Date(currentTime.getFullYear(), 11, 31),
dateFormat: "yy/mm/dd",
onSelect: function( selectedDate ) {
var option = this.id == "report2from1" ? "minDate" : "maxDate",
instance = $( this ).data( "datepicker" ),
date = $.datepicker.parseDate(
instance.settings.dateFormat ||
$.datepicker._defaults.dateFormat,
selectedDate, instance.settings );
dates1.not( this ).datepicker( "option", option, date );
if ( this.id == "report2from1" ){
dates1.not( this ).datepicker( "setDate", date );
}
}
});
$('#report2from2').attr('readonly','readonly');
$('#report2to2').attr('readonly','readonly');
var dates2 = $( "#report2from2, #report2to2" ).datepicker({
showButtonPanel: true,
changeMonth: true,
changeYear: true,
numberOfMonths: 1,
minDate: new Date(2010, 1 -1, 1),
maxDate: new Date(currentTime.getFullYear(), 11, 31),
dateFormat: "yy/mm/dd",
onSelect: function( selectedDate ) {
var option = this.id == "report2from2" ? "minDate" : "maxDate",
instance = $( this ).data( "datepicker" ),
date = $.datepicker.parseDate(
instance.settings.dateFormat ||
$.datepicker._defaults.dateFormat,
selectedDate, instance.settings );
dates2.not( this ).datepicker( "option", option, date );
if ( this.id == "report2from2" ){
dates2.not( this ).datepicker( "setDate", date );
}
}
});
});
The Datepicker plugin has an option to do automatically what you are looking: altField
Here’s how I would optimize your code:
DEMO