您好我正在尝试创建一个预订表单,其中用户只能选择1到14天(从当前日期+1)。我得到的问题是EndDate(此处为#til)设置为从今天起的14天。因此,如果我在StartDate上发表一个月(这里是#fra),我就无法在EndDate中选择任何内容。
如何设置EndDate相对于StartDate设置?
$( function valgavdato() {
var dateFormat = "mm/dd/yy",
from = $( "#fra" )
.datepicker({
minDate: '0+',
defaultDate: "+1w",
changeMonth: true,
numberOfMonths: 1
})
.on( "change", function() {
to.datepicker( "option", "minDate", getDate( this ) );
}),
to = $( "#til" ).datepicker({
maxDate: '14+',
defaultDate: "+1w",
changeMonth: true,
numberOfMonths: 1
})
.on( "change", function() {
from.datepicker( "option", "maxDate", getDate( this ) );
});
function getDate( element ) {
var date;
try {
date = $.datepicker.parseDate( dateFormat, element.value );
} catch( error ) {
date = null;
}
return date;
}
} );
答案 0 :(得分:0)
事情是,maxDate
在加载时设置为"今天" +14。
您必须计算14天+选择日期...
所以,这是有用的东西 可能不是最干净的编码方式...... 但仍然......它有效。
唯一的更改(添加)在#fra
更改时。
$( function valgavdato() {
var dateFormat = "mm/dd/yy",
to_MaxDate = 14; // From date + this = to maxDate
from = $( "#fra" )
.datepicker({
minDate: '0+',
defaultDate: "+1w",
changeMonth: true,
numberOfMonths: 1
})
.on( "change", function() {
var PickedDate = getDate( this );
// See that date is in UTC format.
console.log( "From DatePicker: "+JSON.stringify(PickedDate) );
// Process the picked date.
var tempDay = PickedDate.getDate() + to_MaxDate; // Add a number of days to the picked date.
var tempMonth = PickedDate.getMonth() + 1; // Because months are zero based.
var tempYear = PickedDate.getYear() + 1900; // Because years are 1900 based
console.log( "Temp date: "+ tempYear+"/"+tempMonth+"/"+tempDay +" --- It may look impossible... But Date() handles it.");
// Create a date object in a UTC format.
var newMaxDate = new Date(Date.UTC(tempYear, tempMonth-1, tempDay, 23, 59, 59));
console.log( "New max date: : "+ JSON.stringify(newMaxDate) );
// Set the minDate ans maxDate options.
to.datepicker( "option", {"minDate": PickedDate, "maxDate": newMaxDate});
}),
to = $( "#til" ).datepicker({
maxDate: '14+',
defaultDate: "+1w",
changeMonth: true,
numberOfMonths: 1
})
.on( "change", function() {
from.datepicker( "option", "maxDate", getDate( this ) );
});
function getDate( element ) {
var date;
try {
date = $.datepicker.parseDate( dateFormat, element.value );
} catch( error ) {
date = null;
}
return date;
}
} );

<link href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.0/jquery-ui.min.js"></script>
<input type="text" id="fra"><br>
<br>
<input type="text" id="til">
&#13;