根据复选框更改日期选择器

时间:2011-12-07 22:15:34

标签: jquery jquery-ui-datepicker

我有2个日期选择器,其中包含按钮窗格中的复选框。我想根据是否选中此框来更改日期选择器。除了日期选择器的实际更改外,一切似乎都在起作用。我想要完成的是:如果选中复选框,日期选择器会显示周数和周一的第一天。如果未选中该框,则不会显示周数,并且一周的第一天是星期日

脚本:

$(".datepicker").datepicker({
  showOn: 'button',
  buttonText: 'Date',
  showButtonPanel: true,
  showWeek: false,
  firstDay: 0,
  beforeShow: function (input, inst) {
    setTimeout(function () {
        var buttonPane = $(input)
            .datepicker("widget")
            .find(".ui-datepicker-buttonpane");
                              var html = "";
        var html = '<div class="broadcastFilter"><input type="checkbox"><label> Use Broadcast calendar </label></div>';
        buttonPane.append(html);
        test.DateSelectionDateEventBind();
        var optionChecked = $('.broadcastFilter input[type="checkbox"]').is(':checked');
        //works fine up until here. 
        buttonPane.click(function () {
            if(optionChecked)
            {
                $(".datepicker").datepicker('option', 'showWeek', true );
                $(".datepicker").datepicker('option', 'firstDay', 1 );
            }
            else
            {
                $(".datepicker").datepicker('option', 'showWeek', false);
                $(".datepicker").datepicker('option', 'firstDay', 0 );
            }
        });
    }, 1);
  },
  onChangeMonthYear: function (input) {
    setTimeout(function () {
        var buttonPane = $(input)
            .datepicker("widget")
            .find(".ui-datepicker-buttonpane");
        var html = '<div><input type="checkbox"><label> Use Broadcast calendar </label></div>';
        buttonPane.append(html);
        test.DateSelectionDateEventBind();
    }, 1);
  }
});

http://jsfiddle.net/dan_vitch/zEper/8/

2 个答案:

答案 0 :(得分:1)

首先,您要检查optionChecked,这是在单击复选框之前确定的,这不会更改复选框的状态。另一方面,您正在收听整个buttonPane的点击事件,而不是复选框的点击事件。第三个问题是,在打开datepicker时,您没有将复选框设置为其先前的值。 (虽然也许你的test对象会处理这个问题,但我还没有看到代码的那一部分,小提琴只是给出了一个错误。)

因此,在正确的状态下初始化复选框:

buttonPane.append(html);
buttonPane.find(':checkbox').prop('checked', $('.datepicker').datepicker('option', 'showWeek'));

收听复选框点击:

buttonPane.find(':checkbox').click(function () {

...当点击它时,不要检查旧的optionChecked属性,该属性不会更改,但检查是否选中了复选框:

if($(this).is(':checked'))

Here's a fiddle that takes care of all of that,但就像现在一样,只要点击该复选框,它就会关闭。但是,当代码恢复以前的状态时,一旦再次单击它,它将以您更改为的方式显示。

答案 1 :(得分:0)

您的主要问题是变量“optionChecked”的范围。在匿名函数内部,您绑定到click事件,optionChecked不存在。

解决此问题的最简单方法是在单击函数中移动声明。

buttonPane.click(function () {
    var optionChecked = $('.broadcastFilter input[type="checkbox"]').is(':checked');

    if(optionChecked) { 
        $(".datepicker").datepicker('option', 'showWeek', true );     
        $(".datepicker").datepicker('option', 'firstDay', 1 );
    }

我认为很有可能(我没有检查)你的日期选择器不会仅通过改变选项来显示变化。您可能不得不在之后调用datepicker的刷新方法。

$('.datepicker').datepicker( "refresh" )