2014-09-06 167 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/