2014-09-06 177 views
0

我有一個複選框。我試圖用another SO question的例子來判斷它是否被選中。Javascript無法選擇複選框

但是,我似乎只能使用document.getElementById查詢元素的狀態。我想按照Stack Overflow的例子來工作。下面的代碼...

<html> 
<br> 
       <label>Select All BOM's</label> 
       <input type="checkbox" id="allboms" name="degbutton"/> 
<br> 


function doSomething() 
    { 
     //does not work 
     if ($("#allboms").checked){ 
      //Do stuff 

      alert('was checked'); 
     } 

     //does not work 
     if ($("#allboms").attr("checked")) { 

      //Do stuff 
      console.log("boooooooooooo"); 
      alert('i1 was checked'); 
     } 

     //works 
     if(document.getElementById("allboms").checked){ 
      //Do stuff 

      alert('is checked '); 
     }else{ 
      alert('is unchecked .....'); 
     } 
</html> 
+0

對於這種形式,它需要是'$(「#allboms」)[0] .checked'(注意'[0]')。 jQuery沒有'.checked'屬性,因此您需要使用jQuery方法來檢查或獲取屬性值。此外,你的代碼是一團糟,因爲根本不起作用。 – 2014-09-06 12:38:26

+0

[jQuery複選框選中狀態更改事件]的可能重複(http://stackoverflow.com/questions/8423217/jquery-checkbox-checked-state-changed-event) – Robert 2014-09-06 12:38:43

+0

您接受的答案不是第一個。答案是提前幾秒斯蒂芬的答案..謝謝.. – 2014-09-06 13:31:16

回答

1

試試這個: -

if ($("#allboms").is(':checked')){ 
    ..... 
} 
1

嘗試

if ($("#allboms").is(':checked')) { 
    .. 
} 
+0

感謝所有答覆,標記第一個答案是正確的......非常感謝所有 – user1843591 2014-09-06 13:24:29

2

這些都是我能想到用普通的JavaScript和jQuery的形式:

$(document).ready(function rd(){ 
    var $allboms = $('#allboms'); 

    $allboms.on('change', function ch(){ 
     if (this.checked) { 
      console.log('this.checked is true.'); 
     } 

     if ($(this)[0].checked) { 
      console.log('$(this)[0].checked is true.'); 
     } 

     if ($(this).prop('checked')) { 
      console.log('$(this).prop("checked") is true.'); 
     } 

     if ($(this).is(':checked')) { 
      console.log('$(this).is(":checked") is true.'); 
     } 
    }); 
}); 

http://jsfiddle.net/dyeu7w77/