2011-09-19 46 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')'的值来确定真/假。 –