问题
I have 2 datepickers, one is a fromDate and one is a toDate. I can highlight the range from the fromDate to the toDate successfully in beforeShowDay(), but I need it to highlight when new values are selected. This triggers the onSelect statement. Is there a way to either:
1) trigger the beforeShowDay again? or
2) get all the dates of the new range and apply a css class to them?
beforeShowDay: function(date){
if (date >= initialFromDate && date <= initialToDate) {
return [true, 'ui-individual-date', ''];
}
else {
return [true, '', ''];
}
},
onSelect: function (dateText, obj) {
var fromDate = new Date(dateText);
var toDate = $(".dateDiv2").datepicker('getDate');
**get individual dates?
if (individualdate >= fromDate && individualDate <= toDate)
apply css class or formatting to individualDate**
},



回答1:
I have done this successfully with a datepicker for a from date and a datepicker for a to date, so I modified it for one datepicker. Here is the code:
$(function () {
var today = new Date();
var thisYear = (today).getFullYear();
var fromDate = '1/1/2000' //this is the initial from date to set the datepicker range
var toDate = '1/7/2000' // this is the initial to date to set the datepicker range
//... initialize datepicker....
},
beforeShowDay: function(date){
//if the date is in range
if (date >= fromDate && date <= toDate) {
return [true, 'ui-individual-date', '']; //applies a css class to the range
}
else {
return [true, '', ''];
}
},
onSelect: function (dateText, obj) {
//sets the new range to be loaded on refresh call, assumes last click is the toDate
fromDate = toDate;
toDate = new Date(dateText);
$(".classDp1").datepicker("refresh");
$(".classDp2").datepicker("refresh");
},
Every time you refresh the beforeShowDay function is called with the new fromDate and toDate range. Having the variables outside the function and modifying them within enables the highlighting from the css to be applied on each click.
回答2:
Link on jsFiddle
HTML:
<div id="dateFrom"></div>
<div id="dateTo"></div>
CSS:
div#dateFrom, div#dateTo { display: inline-block; }
.ui-individual-date { background: yellow; }
JS:
$( function() {
$( "#dateFrom, #dateTo" ).datepicker( {
beforeShowDay: function( date ){
var initialFromDate, initialToDate;
initialFromDate = $("#dateFrom").datepicker('getDate');
initialToDate = $("#dateTo").datepicker('getDate');
if ( date >= initialFromDate && date <= initialToDate ) {
return [ true, 'ui-individual-date', '' ];
} else {
return [ true, '', '' ];
}
},
onSelect: function ( dateText, obj ) {
$( "#dateFrom" ).datepicker( "refresh" );
$( "#dateTo" ).datepicker( "refresh" );
}
} );
} );
Just in beforeShowDay change initialFromDate
and initialToDate
to $("#dateFrom").datepicker('getDate')
and $("#dateTo").datepicker('getDate')
.
And in onSelect
use $( "#dateFrom" ).datepicker( "refresh" );
and $( "#dateTo" ).datepicker( "refresh" );
.
来源:https://stackoverflow.com/questions/29085489/datepicker-onselect-to-format-new-date-range