两个jQuery UI datepickers具有不同的选项

时间:2015-03-14 05:15:41

标签: jquery jquery-ui jquery-ui-datepicker

示例在这里http://jsfiddle.net/68z9dkyb/5/

有2个日期选择器。

<input type="text" class="datepicker" id="date_first_registration">
<input type="text" class="datepicker" id="inspection_valid_until">

对于一个想要的日期范围,从今年前100年开始到今年结束。另一个是在一年之前开始,在今年之后的20年结束。

试过这个:

$(function() {
    $(".datepicker").datepicker({
        inline: true,
        showOtherMonths: true,
        changeMonth: true,
        changeYear: true,
        dayNamesMin: ["Sun", "Mon", "Tue", "Wed", "Thu", "Frid ", "Sat"],
        dateFormat: "yy-mm-dd"
    }).val()
    $("#date_first_registration").datepicker({
        yearRange: "-100:+0"
    }).val()
    $("#inspection_valid_until").datepicker({
        yearRange: "-1:+20"
    }).val()
});

但是不起作用。根据我的理解,我为.datepicker设置了所有内容,然后为每个ID设置不同的日期范围。但是不起作用。需要纠正什么?

2 个答案:

答案 0 :(得分:2)

1:您可以使用option参数:

$(function() {
  $(".datepicker").datepicker({
    showOtherMonths: true,
    changeMonth: true,
    changeYear: true,
    dayNamesMin: ["Sun", "Mon", "Tue", "Wed", "Thu", "Frid ", "Sat"],
    dateFormat: "yy-mm-dd"
  });
  $("#date_first_registration").datepicker("option", "yearRange", "-100:+0");
  $("#inspection_valid_until").datepicker("option", "yearRange", "-1:+20");
});
@import url("//ajax.googleapis.com/ajax/libs/jqueryui/1.11.1/themes/redmond/jquery-ui.min.css");
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.1/jquery-ui.min.js"></script>

<input class="datepicker" id="date_first_registration">
<input class="datepicker" id="inspection_valid_until">

2:替代方法是使用对象和jQuery.extend

$(function() {
  var defaults = {
    showOtherMonths: true,
    changeMonth: true,
    changeYear: true,
    dayNamesMin: ["Sun", "Mon", "Tue", "Wed", "Thu", "Frid ", "Sat"],
    dateFormat: "yy-mm-dd"
  };
  $("#date_first_registration").datepicker($.extend({}, defaults, {
    yearRange: "-100:+0"
  }));
  $("#inspection_valid_until").datepicker($.extend({}, defaults, {
    yearRange: "-1:+20"
  }));
});
@import url("//ajax.googleapis.com/ajax/libs/jqueryui/1.11.1/themes/redmond/jquery-ui.min.css");
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.1/jquery-ui.min.js"></script>

<input class="datepicker" id="date_first_registration">
<input class="datepicker" id="inspection_valid_until">

答案 1 :(得分:1)

删除.datepicker类通用代码,并为每个日期选择器实现单独的代码,如

$("#date_first_registration").datepicker({ 
    changeMonth: true,
    changeYear: true,
    dayNamesMin: ["Sun", "Mon", "Tue", "Wed", "Thu", "Frid ", "Sat"],  
yearRange: "-100:+0"
}).val()


$("#inspection_valid_until").datepicker({ 
    changeMonth: true,
    changeYear: true,
    dayNamesMin: ["Sun", "Mon", "Tue", "Wed", "Thu", "Frid ", "Sat"],  
    yearRange: "-1:+20"
}).val()

Demo