【问题标题】:Select all checkbox in div选中div中的所有复选框
【发布时间】:2014-11-23 23:53:06
【问题描述】:

我有以下功能来选择/取消选择所有复选框。

$(function () {
        $("#selectall").click(function () {           
            $('.Employee').attr('checked', this.checked);
        });
        $(".Employee").click(function () {
            if ($(".Employee").length == $(".Employee:checked").length) {
                $("#selectall").attr("checked", "checked");
            } else {
                $("#selectall").removeAttr("checked");
            }

        });
    });

它工作正常,但我可以在第一次页面加载时选择/取消选择全部,第二次我需要重新加载页面。意味着它没有提供多次选择/取消选择功能。

【问题讨论】:

  • 你能在这里设置一个 Fiddle 吗? jsfiddle.net?
  • 你的 (MCVE) HTML 是什么?
  • 也请给我们您的 HTML 结构。会有很大帮助的!
  • 你应该做一个刷新功能?查看此页面以获取您的 .attr();这就是问题所在。 if ( $( elem ).is( ":checked" ) api.jquery.com/attr
  • 您需要使用.change() jquery 函数,如本页回答:stackoverflow.com/questions/9180087/…

标签: javascript jquery


【解决方案1】:

第一个问题是您需要使用.prop() 方法。这将读取 javascript checked 属性。使用 HTML checked 属性对第一个实例有效,但对其余实例无效。接下来,您需要稍微修改一下您的逻辑。我已经举了一个例子。观察javascript函数。最后,您应该使用change 方法,或者最好使用.on('change', function(){ ... }),但我会让我的示例更接近您的原始帖子。

$(function () {
        $("#selectall").change(function () {
            $('.Employee').prop('checked', this.checked);
        });
        $(".Employee").change(function () {
            if ($(".Employee").length == $(".Employee:checked").length) {
                $('#selectall').prop('checked', this.checked);
            } else {
                $('#selectall').prop('checked', false);
            }
        });
    });
label {
  display:block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <label>test 1: <input type="checkbox" class="Employee"></label>
  <label>test 2: <input type="checkbox" class="Employee"></label>
  <label>test 3: <input type="checkbox" class="Employee"></label>
  <label>test 4: <input type="checkbox" class="Employee"></label>
  <label>test 5: <input type="checkbox" class="Employee"></label>
</div>

<label>Select All: <input id="selectall" type="checkbox"></label>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-18
    • 1970-01-01
    • 1970-01-01
    • 2018-04-13
    • 2010-10-27
    相关资源
    最近更新 更多