【问题标题】:button that will uncheck all checkboxes?取消选中所有复选框的按钮?
【发布时间】:2016-05-03 02:13:44
【问题描述】:

我有一个存储在 cookie 中的复选框。

这里是jquery代码:

//JQuery that will set the checkbox in it's current state
 $("#checkAll").on("change", function() {
    $(':checkbox').not(this).prop('checked', this.checked);
  });

  $(":checkbox").on("change", function(){
    var checkboxValues = {};
    $(":checkbox").each(function(){
      checkboxValues[this.id] = this.checked;
    });
    $.cookie('checkboxValues', checkboxValues, { expires: 7, path: '/' })
  });

  function repopulateCheckboxes(){
    var checkboxValues = $.cookie('checkboxValues');
    if(checkboxValues){
      Object.keys(checkboxValues).forEach(function(element) {
        var checked = checkboxValues[element];
        $("#" + element).prop('checked', checked);
      });
    }
  }

  $.cookie.json = true;
  repopulateCheckboxes();

上面的代码完美运行,但是当我尝试使用按钮取消选中它们时,它根本没有取消选中。

这是我使用的函数:

 $("#UncheckAll").click(function(){
   $("input[type='checkbox']").prop('checked',false);
});

我该怎么办?谁能帮帮我。

【问题讨论】:

  • 你知道点击回调是否触发了吗?是否清除了某些复选框,但不是全部?
  • 复选框正在清除,但在刷新页面后它又回到被选中状态。
  • 然后在页面加载时清除您的 cookie
  • 页面刷新将导致调用repopulateCheckboxes()。假设该功能按预期工作,当然复选框状态将恢复!
  • 你如何解决这个问题?

标签: jquery cookies checkbox


【解决方案1】:

为所有复选框赋予一个类,例如 myclass。然后使用jQuery。

document.ready函数中删除你的cookie

 $.cookie("checkboxValues", null);//checkboxValues is the name of your cookie

对于 jQuery 1.6+

$("#UncheckAll").click(function(){
   $('input:checkbox:checked.myclass').prop('checked',false);
});

对于 jquery 1.5-

$("#UncheckAll").click(function(){
   $('input:checkbox:checked.myclass').attr('checked',false);
});

【讨论】:

    【解决方案2】:

    试试这个

     $("#UncheckAll").click(function(){
       $('input:checkbox.class').prop('checked',false);
    });
    

    如果没有公共类,则为 this

     $("#UncheckAll").click(function(){
       $(':checkbox').prop('checked',false);
    });
    

    【讨论】:

      猜你喜欢
      • 2021-12-06
      • 2013-06-08
      • 2018-04-14
      • 2014-05-23
      • 2019-02-14
      • 1970-01-01
      • 2014-04-29
      • 2014-09-24
      相关资源
      最近更新 更多