2011-12-07 52 views
0

我有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/

回答

1

一件事你總是爲optionChecked這是被點擊前面的複選框,不改變複選框的狀態決定檢查。另一方面,您正在聆聽整個buttonPane的點擊事件,而不是複選框的點擊事件。第三個問題是在打開日期選擇器時,您沒有將複選框設置爲之前的值。 (雖然也許你的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,但現在它只要點擊複選框就會關閉。然而,當代碼恢復以前的狀態時,一旦你再次點擊它,它就會以你改變它的方式顯示出來。

+0

優秀的答案。非常感謝所有的幫助。 –

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") 
相關問題