0

我有这段代码,我需要设置条件来检查我的复选框是否被选中。

HTML:

   <div id="checkbox_group">
     <input type="checkbox" value="21" name="">21
     <input type="checkbox" value="16" name="">16
     <input type="checkbox" value="20" name="">20
   </div>

jQuery:

$('#checkbox_group input[type=checkbox]').click(function() { 
    if (/* Condition to check if checkbox is checked */)) {
        // if is checked then after click change to false like: checked="false"
    }
    else {
        // if is NOT checked then change it like checked="true"
    }
});
4

2 回答 2

2

使用选中的属性。

现场演示

$('#checkbox_group input[type=checkbox]').click(function() {    
    if (this.checked) {
        $(this).siblings('input[type=checkbox]').prop('checked', false);
    }
    else {
        // if is NOT checked then check it liek checked="true"
        $(this).siblings('input[type=checkbox]').prop('checked', true);
    }
});

如果您只有复选框作为需要参与的兄弟,则可以省略兄弟中的选择器。

现场演示

$('#checkbox_group input[type=checkbox]').click(function() {    
    if (this.checked) 
        $(this).siblings().prop('checked', false);  
    else        
        $(this).siblings().prop('checked', true);    
});
于 2013-07-16T14:46:21.907 回答
1

尝试is(':checked')

$('#checkbox_group input[type=checkbox]').click(function() { 
 if ($(this).is(':checked')) {

           //do something
  }else{
           //do something
  }

});
于 2013-07-16T14:47:13.583 回答