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

Come posso utilizzare il parametro 'inst' di onChangeMonthYear per auto-selezionare il primo giorno del mese?jQuery UI datepicker onChangeMonthYear e il parametro inst

vedi: http://jsfiddle.net/sD8rL/

Attualmente sto usando il codice qui sotto, ma mi sento come dovrei essere in grado di utilizzare la variabile 'inst' in un modo più diretto.

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

risposta

8

Se non v'è alcuna ragione particolare che si desidera utilizzare inst, si può sempre usare this:

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

vedere in azione: http://jsfiddle.net/william/sD8rL/2/.

+0

Questo ha senso, in realtà non avevo alcun motivo particolare per usare "inst", "questo" funziona alla grande. – ActionOwl

1

Soluzione di William Niu non considera altri formati di data (come gg-mm-aaaa). Faresti meglio a prendere un oggetto Date dal tuo datepicker e modificarlo nel modo che preferisci (ad esempio, impostando il primo giorno del mese). Dopo le tue modifiche, puoi ri-passare l'oggetto Data modificato al tuo 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); 
    } 

In questo modo non sarà possibile sovrascrivere il formato della data (eventualmente impostata durante l'inizializzazione datepicker);)

Prestare attenzione al formato mese: datepicker gestisce un formato 1-12 per mesi, mentre l'oggetto Date è 0-11.

Spero che questo possa aiutare, ciao!

Problemi correlati