【问题标题】:loop through checkboxes by classname in jquery在jquery中按类名循环复选框
【发布时间】:2017-03-10 04:55:54
【问题描述】:

我需要遍历所有复选框来设置按钮是否禁用。如果选中其中一个复选框,则该按钮已启用。但是,看起来我的代码没有通过复选框循环。每个函数里面的警告没有显示。我在 How to loop through group of check boxes that have same class name?找到了循环方法

这是我的代码:

function setButton() {

                alert('line 24');
                var blnDisable = true;

                //https://stackoverflow.com/questions/35506843/how-to-loop-through-group-of-check-boxes-that-have-same-class-name
                $('.chkItem').each(function (index, obj) {
                    if (obj.checked == true) {
                        alert('line 30');
                        blnDisable = false;
                    }

                });
                alert('disable=' + blnDisable);
                    $("#btnDownload").attr("disabled", blnDisable);

            }

【问题讨论】:

  • obj 将是一个 jQuery 对象 - jQuery 对象没有 checked 属性 - 使用 this 的实例 - if (this.checked)
  • @tymeJV Im pretty sur obj 将是一个 HTML 元素。 @op 什么时候调用 setButton?
  • 或内置jquery“prop”函数:if(obj.prop("checked"))
  • @Karl-AndréGagnon -- 是的,你是对的,不知道为什么我认为它是一个 jQ 对象。

标签: jquery checkbox


【解决方案1】:

这将使它检查是否选中了任何复选框。如果是,它将启用该复选框,如果不是,它将禁用它。最后,我将它分配给一个函数,以便它可以在页面加载时运行。这很重要,因此它会自动检查是否应在页面 laod 上启用下载按钮。

<input type="checkbox" class="chkItem" />one<br />
<input type="checkbox" class="chkItem" />two<br />
<input type="checkbox" class="chkItem" />three<br />
<button id="btnDownload">download</button>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script>


var checkButton = function () {
    blnDisable = true;

    $('.chkItem').each(function (index, obj) {
        if (this.checked === true) {
            blnDisable = false;
        }
    });

    $("#btnDownload").attr("disabled", blnDisable);
};

$(".chkItem").on("change", checkButton);

checkButton();

</script>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-06
    • 2012-02-11
    • 2020-04-19
    • 2017-09-01
    • 1970-01-01
    相关资源
    最近更新 更多