在jQuery datepicker中更改可选日期以获取不同的表单,同时保持其他选项相同并且干

时间:2015-04-22 09:57:30

标签: jquery datepicker jquery-ui-datepicker

我要做的就是保留我的日期选择程序DRY的代码,但我似乎无法让我的更改正常工作。我想在所有日期选择器中保留一组通用选项:

var dateToday = new Date(); 
$(".selectdate").datepicker({
    dateFormat: 'd MM yy',
    showOtherMonths: true,
    selectOtherMonths: true
});

但接下来有一些日期选择器我需要maxDate选项而其他我需要minDate选项但是我无法使用它。例如:

$("#calldate").datepicker({
    maxDate: dateToday
});

所以我有一个id' calldate'的输入字段。和班级选择日期'并且会认为这会起作用但它不会 - 日历显示所有选项设置为$(' .selectdate')....但是maxDate不起作用。而我不想要的是为我拥有的每个日期选择器重复代码,如下所示:

$("#fromdate").datepicker({
    dateFormat: 'd MM yy',
    showOtherMonths: true,
    selectOtherMonths: true,
    minDate: dateToday
});

$("#calldate").datepicker({
    dateFormat: 'd MM yy',
    showOtherMonths: true,
    selectOtherMonths: true,
    maxDate: dateToday
});

我希望这是有道理的,有人可以帮助我排序,谢谢

1 个答案:

答案 0 :(得分:1)

您可以使用$.datepicker.setDefaults(),然后在您希望应用更多/不同选项的元素上调用.datepicker()时覆盖/添加新选项,如下所示:



$.datepicker.setDefaults({
    dateFormat: 'd MM yy',
    showOtherMonths: true,
    selectOtherMonths: true
});

$('#fromdate').datepicker();
$('#calldate').datepicker({ minDate: 0 });

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.3/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.3/jquery-ui.min.js"></script>


<label>#calldate
  <input type="text" id="calldate" min='0'/>
</label>
<label>#fromdate
  <input type="text" id="fromdate"/>
</label>
&#13;
&#13;
&#13;