2011-09-12 28 views
7
$('.selector').datepicker({ 
    onChangeMonthYear: function(year, month, inst) { ... } 
}); 

如何使用的onChangeMonthYear到“出师表”参数自动选择每月的第一天?jQuery UI的日期选择器onChangeMonthYear和研究所参数

见:http://jsfiddle.net/sD8rL/

我目前使用下面的代码,但我觉得我应该能够使用“出师表”变量更直接的方式。

$(".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 
     } 
    }); 

回答

8

如果要使用inst没有特别的原因,你可以随时使用this

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

看到它在行动:http://jsfiddle.net/william/sD8rL/2/

+0

这使得完全意义上我没有任何特别的理由使用'inst','这个'很好。 – ActionOwl

1

William Niu的解决方案不考虑其他日期格式(如dd-mm-yyyy)。 您最好从datepicker中获取Date对象,然后按照您喜欢的方式修改它(即设置每月的第一天)。修改之后,您可以将修改后的Date对象重新传递给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); 
    } 

这样你不会覆盖日期格式(日期选择器初始化过程中可能设置);)

注重月份格式:日期选择器句柄月1-12格式,而Date对象是0-11。

希望这可以帮助,再见!