2011-09-19 41 views
0

我有一個js腳本可以幫助我創建一個cookie。它會保存選中的複選框,以便記住此值(在Cookie中設置)。現在的問題是,它似乎不能用單選按鈕。閱讀js文件時,我看到輸入類型=複選框。所以這是合乎邏輯的,它忽略了單選按鈕。jquery cookie腳本只記住複選框而不是單選按鈕

如何更改此腳本,使其不僅可以檢查選中的複選框,還可以檢查已選中的單選按鈕?

非常感謝

我的js文件的腳本:

jQuery(document).ready(function(){ 

    new chkRemembrance(); 

}); 

function chkRemembrance(){ 
    this.__construct(); 
} 

chkRemembrance.prototype = { 

    __construct : function(){ 
     this.chk = this.fetchData(); // initialise array to store the checkboxes 
     this.init(); 
    }, 

    init : function(){ 
     // first initialise all checkboxes that are checked 
      for(c in this.chk){ 
       $("input[type=checkbox]#" + c).attr('checked', this.chk[c]); 
      } 
     // now make sure we fetch the checkbox events 
     var o = this; 
     $("input[type=checkbox]").change(function(){ 
      o.saveData(this.id, this.checked); 
     }) 
    }, 

    fetchData : function(){ 
     var r = {}; 
     if ($.cookie('chk')){ 
      r = JSON.parse($.cookie('chk')); 
     } 
     return r; 
    }, 

    saveData : function(id,status){ 
     this.chk[id] = status; 
     $.cookie('chk', JSON.stringify(this.chk)); 
    } 

} 

回答

0

它看起來像你應該能夠在單選按鈕添加,它會工作。

更改此:

$("input[type=checkbox]#" + c).attr('checked', this.chk[c]); 

要這樣:

$("input[type=checkbox]#" + c + ", input[type=radio]#" + c).attr('checked', this.chk[c]); 

並改變這一點:

$("input[type=checkbox]").change(function(){...}); 

要這樣:

$("input[type=checkbox], input[type=radio]").change(function(){...}); 
+0

謝謝。我已經嘗試過,但似乎沒有工作。也許我的廣播html是錯的? : \t \t ' – Maurice

+0

你可以嘗試改變檢查check-ness的行:'o.saveData(this.id,this.checked);'=>'o.saveData(this.id,$(this).attr(' '');' –

+0

或者,使用'$(this).attr('checked')'的值來確定真/假。 –