2017-03-09 71 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>