2017-03-09 69 views
0

我需要遍历所有复选框来设置按钮禁用或不。如果其中一个复选框被选中,则该按钮被启用。然而,它看起来像我的代码没有循环通过复选框。每个函数内的警报不shown.I发现 How to loop through group of check boxes that have same class name?通过在jquery中的classname循环复选框

的循环方法,还有就是我的代码:

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); 

      } 
+0

'obj'将是一个jQuery对象 - jQuery的对象没有一个'checked'属性 - 使用'this'的实例 - '如果(this.checked)' – tymeJV

+0

@tymeJV Im相当河畔' obj'将是一个HTML元素。 @op什么时候setButton被调用? –

+0

或内置的jquery“prop”函数:'if(obj.prop(“checked”))' – MacPrawn

回答

0

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

<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>