我在jQueryMobile中使用jQuery-Mobile-DateBox作为日期和时间选择器。
<input id="start" type="date" data-role="datebox" data-options='{"mode": "calbox", "afterToday": true, "useFocus": true, "overrideDateFormat": "%m/%d/%Y"}'>
<input id="end" type="date" data-role="datebox" data-options='{"mode": "calbox", "afterToday": true, "useFocus": true, "overrideDateFormat": "%m/%d/%Y"}'>
我不需要允许用户选择开始日之前的结束日。
$("#end").datebox("minDays", $("#start").val());
上述代码不起作用。
答案 0 :(得分:2)
以下是根据选择开始日期或结束日期的方式禁用日期:
如果在开始日期框中选择了日期,则结束日期将限制为选择开始日期之后的天数(包括开始日期)和结束日期的视图。
$(document).on('pageinit', '#index', function(){
$('#end-date').bind('datebox', function(e, p) {
if ( p.method === 'open') {
// Make it a date
var startDate = new Date($('#start-date').val());
var todaysDate = new Date();
// Length of 1 Day
var lengthOfDay = 24 * 60 * 60 * 1000;
// Get the difference
var diff = parseInt((((startDate.getTime() - todaysDate.getTime()) / lengthOfDay)+1)*-1,10);
// Set minDays to disallow anything earlier
$('#end-date').datebox({'minDays': diff});
}
});
$('#start-date').bind('datebox', function(e, p) {
if ( p.method === 'open') {
// Make it a date
var endDate = new Date($('#end-date').val());
var todaysDate = new Date();
// Length of 1 Day
var lengthOfDay = 1000 * 60 * 60 * 24;
// Get the difference
var diff = parseInt((((endDate.getTime() - todaysDate.getTime()) / lengthOfDay)+1),10);
// Set minDays to disallow anything earlier
$('#start-date').datebox({'maxDays': diff});
}
});
});
检查更新的小提琴链接:http://jsfiddle.net/QTuma/6/
或者根据以下解决方案,设置min和max的简单方法:
$(document).on('pageinit', '#index', function(){
$('#start-date').bind('datebox', function(e, p) {
if ( p.method === 'set') {
var endDate = $('#start-date').val().replace(/(\d{1,2})\/(\d{1,2})\/(\d{4})$/,'$3-$1-$2');
$('#end-date').attr({'min':endDate,'max':'2999-01-01'});
$('#end-date').datebox('applyMinMax');
}
});
$('#end-date').bind('datebox', function(e, p) {
if ( p.method === 'set') {
var endDate = $('#end-date').val().replace(/(\d{1,2})\/(\d{1,2})\/(\d{4})$/,'$3-$1-$2');
$('#start-date').attr({'min':'1000-01-01','max':endDate});
$('#start-date').datebox('applyMinMax');
}
});
});
答案 1 :(得分:2)
如果您想阻止结束日低于开始日
工作示例:http://jsfiddle.net/Gajotres/QTuma/
<label for="start-date">Start Date</label>
<input name="start-date" id="start-date" type="date" data-role="datebox" data-options='{"mode": "calbox", "useNewStyle":true,"overrideDateFormat":"%-m/%-d/%Y"}'/>
<label for="end-date">End Date</label>
<input name="end-date" id="end-date" type="date" data-role="datebox" data-options='{"mode": "calbox", "useNewStyle":true,"overrideDateFormat":"%m/%-d/%Y"}'/>
$('#end-date').bind('datebox', function(e, p) {
if ( p.method === 'set' && $('#start-date').val().length > 0) {
e.stopImmediatePropagation();
var startDate = new Date($('#start-date').val());
var endDate = new Date($('#end-date').val());
if (startDate > endDate)
{
$('#end-date').val('');
}
}
});