I am using the jquery datepicker, but when the user changes the month, it automaticaly changes the year to the year set as min date. I don't understand why this happens and it seems to happen randomly as well.
This is my function:
function DatePickerShort() {
$(":input[datepicker]").each(function () {
ShowPicker($(this));
$(this).bind('focus', function () {
ShowPicker($(this));
});
});
function ShowPicker(obj) {
if ($(obj).is('[readonly]')) {
$(obj).datepicker('destroy');
}
else {
$(obj).datepicker('destroy');
var fecha = new Date();
$(obj).datepicker({
changeMonth: true,
changeYear: true,
minDate: new Date(2000, 08, 01),
firstDay: 1,
dayNamesMin: ['Do', 'Lu', 'Ma', 'Mi', 'Ju', 'Vi', 'Sa'],
dateFormat: 'dd/mm/yy',
monthNamesShort: ['Ene', 'Feb', 'Mar', 'Abr', 'May', 'Jun', 'Jul', 'Ago', 'Sep', 'Oct', 'Nov', 'Dic'],
});
}
}
}
I am making a lot of assumptions since you did provide any clarity about the html. For a better answer, please post the html as well.
What I think you are trying to accomplish: You are attempting to activate the datepicker when you focus on an input element that has a datepicker attribute. If it is a readonly element, you don't want to show the datepicker.
What you are actually doing: You are finding all the input elements marked with datepicker attribute and creating a datepicker. Although, to be honest, I am not sure how the selector is working without looking at your html. Then, every time the input gets focus, the datepicker is destroyed and you are creating a brand new one. When the user selects a date, the input loses focus. When the datepicker puts the date back in, it gains focus and the new datepicker is replaced again. It is probably intermittent depending on whether the focus event (creating a new datepicker) happens before or after the input box is populated.
The Fix:
$("input[datepicker]:not([readonly])").datepicker({
changeMonth: true,
changeYear: true,
minDate: new Date(2000, 08, 01),
firstDay: 1,
dayNamesMin: ['Do', 'Lu', 'Ma', 'Mi', 'Ju', 'Vi', 'Sa'],
dateFormat: 'dd/mm/yy',
monthNamesShort: ['Ene', 'Feb', 'Mar', 'Abr', 'May', 'Jun', 'Jul', 'Ago', 'Sep', 'Oct', 'Nov', 'Dic']
});
as JazZRo said in his comment, just setup the datepicker once.
My preference is to tag the datepickers with a class and use that as the selector. It performs better and is more clear. If you can, just tag the datepickers with a class and don't tag the readonly ones.
Keep in mind that you need if readonly is false, it still won't get the datepicker because the selector is just checking for the existence of the readonly attribute (same with datepicker attribute). See this JSfiddle for an example: http://jsfiddle.net/DanCaveman/RBtY5/4/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With