Thanks to techfoobar, I have a datepicker with a synchronised input field and a select list.
However, when I have changed the format of the date to “yy-mm-dd”, it stopped working. A change in the select list triggers the change in the input, but clicking the datepicker won’t update the select list.
Here is the script:
$(function() {
$('#selectedDatepicker').datepicker({
dateFormat: "yy-mm-dd",
beforeShow: readSelected, onSelect: updateSelected,
minDate: new Date(2013, 1 - 1, 1), maxDate: new Date(2013, 06 - 1, 31),
numberOfMonths: 3,
showButtonPanel: true,
showOn: 'both', buttonImageOnly: true, buttonImage: 'http://jqueryui.com/resources/demos/datepicker/images/calendar.gif'});
// Prepare to show a date picker linked to three select controls
function readSelected() {
$('#selectedDatepicker').val($('#selectYear').val() + '-' +
$('#selectDay').val());
return {};
}
// Update three select controls to match a date picker selection
function updateSelected() {
var date1 = $(this).val();
console.log(date1.substring(3, 5));
console.log(date1.substring(6, 10));
$('#selectDay').val(date1.substring(3, 5));
$('#selectYear').val(date1.substring(6, 10));
}
$('select').change(readSelected);
});
This is the HTML code:
<select id="selectDay">
<option value="01">1</option>
<option value="02">2</option>
<option value="03">3</option>
<option value="04">4</option>
...
</select>
<select id="selectYear">
<option value="2013-01">January 2013</option>
<option value="2013-02">February 2013</option>
<option value="2013-03">March 2013</option>
<option value="2013-04">April 2013</option>
<option value="2013-05">May 2013</option>
<option value="2013-06">June 2013</option>
</select>
<p>Date: <input type="text" id="selectedDatepicker" /></p>
You can check the fiddle here:
Where does this problem come from? Both of the fields have the same format set.
The value you are trying to select in the select element does not exist, because the substring yields a different value than it originally did. You need to adjust your
substraccordingly.jsfiddle