JQuery UI datepicker onChangeMonthYear and inst parameter

$('.selector').datepicker({ onChangeMonthYear: function(year, month, inst) { ... } }); 

How can I use the "inst" onChangeMonthYear parameter to automatically select the first day of the month?

see http://jsfiddle.net/sD8rL/

I am currently using the code below, but it seems to me that I can use the "inst" variable in a more direct way.

  $(".datepicker" ).datepicker({ changeMonth: true, changeYear: true, maxDate:0, onChangeMonthYear: function(year, month, inst){ // set date to 1st on year or month change // this seems bit janky, but works $('#' + inst.id).datepicker( "setDate", month + '/1/' + year ); // Can't I use the instatnce to set the date? // $(inst).datepicker( "setDate", month + '/1/' + year ); // fails // inst.datepicker( "setDate", month + '/1/' + year ); // fails // inst.selectedDay = 1; // fails // inst.currentDay = 1; // fails } }); 
+7
source share
2 answers

Unless there are special reasons why you want to use inst , you can always use this :

  onChangeMonthYear: function(year, month, inst){ $(this).datepicker( "setDate", month + '/1/' + year ); } 

See in action: http://jsfiddle.net/william/sD8rL/2/ .

+8
source

William Niu's solution does not consider other date formats (e.g. dd-mm-yyyy). You better get the Date object from your datepicker and change it the way you like (i.e. Set the first day of the month). After your modifications, you can resubmit the modified Date object to your datepicker.

  dateFormat: "dd-mm-yy", onChangeMonthYear: function(year, month, inst){ var selectedDate = $(this).datepicker( "getDate" );//Date object selectedDate.setDate(1);//set first day of the month selectedDate.setMonth(month-1);//month is 1-12, setMonth is 0-11 selectedDate.setFullYear(year); $(this).datepicker( "setDate", selectedDate ); } 

This way you will not overwrite the date format (possibly set during date initialization);)

Pay attention to the format of the month: datepicker processes the 1-12 format for several months, and the Date object 0-11.

Hope this helps, bye!

+1
source

All Articles