91

我想检查一个复选框是否刚刚被取消选中,当用户点击它时。这样做的原因是因为我想在用户取消选中复选框时进行验证。因为至少需要选中一个复选框。因此,如果他取消选中最后一个,那么它会自动再次检查自己。

使用 jQuery,我可以很容易地找出它是否被选中:

$('#check1').click(function() {
    if($(this).is(':checked'))
        alert('checked');
    else
        alert('unchecked');
});

但我实际上只想有一个 if 语句来检查复选框是否未被选中。

所以我想我可以用下面的代码做到这一点:

$('#check2').click(function() {
    if($(this).not(':checked'))
        alert('unchecked');
    else
        alert('checked');
});

但这将始终显示“未检查”消息。真的不是我所期待的……

演示:http: //jsfiddle.net/tVM5H/

所以最终我需要类似的东西:

$('#check2').click(function() {
    if($(this).not(':checked')) {
        // Got unchecked, so something!!!
    }
});

但显然这行不通。我不想使用第一个示例,因为当我只需要一个“if”语句时,我会有一个不必要的“else”语句。

所以首先,这是一个 jQuery 错误吗?因为对我来说这是出乎意料的行为。其次,有人有什么好的选择吗?

4

8 回答 8

177

尝试这个:

if(!$(this).is(':checked'))

演示

于 2012-06-22T15:24:03.737 回答
61

The answer already posted will work. If you want to use the jQuery :not you can do this:

if ($(this).is(':not(:checked)'))

or

if ($(this).attr('checked') == false)
于 2012-06-22T15:27:25.137 回答
7

jQuery to check for checked? Really?

if(!this.checked) {

Don't use a bazooka to do a razor's job.

于 2012-06-22T15:26:05.340 回答
6
$(document).ready(function() {
        $("#check1").click(function() {
            var checked = $(this).is(':checked');
            if (checked) {
                alert('checked');
            } else {
                alert('unchecked');
            }
        });
    });
于 2013-10-06T02:47:56.897 回答
3
<script type="text/javascript">

 if(jQuery('input[id=input_id]').is(':checked')){
  // Your Statment
 }else{
  // Your Statment
 }

 OR

 if(jQuery('input[name=input_name]').is(':checked')){
  // Your Statment
 }else{
  // Your Statment
 }

</script>

代码取自这里:http ://chandreshrana.blogspot.in/2015/10/how-to-check-if-checkbox-is-checked-or.html

于 2016-03-10T06:29:13.203 回答
2

Check out some of the answers to this question - I think it might apply to yours:

how to run click function after default behaviour of a element

I think you're running into an inconsistency in the browser implementation of the onclick function. Some choose to toggle the checkbox before the event is fired and some after.

于 2012-06-22T15:27:47.313 回答
1

答案已经发布了。但是我们也可以以这种方式使用jquery

演示

$(function(){
    $('#check1').click(function() {
        if($('#check1').attr('checked'))
            alert('checked');
        else
            alert('unchecked');
    });

    $('#check2').click(function() {
        if(!$('#check2').attr('checked'))
            alert('unchecked');
        else
            alert('checked');
    });
});
于 2013-09-23T12:53:49.307 回答
0

像这样做

if (typeof $(this).attr("checked") == "undefined" )

// To check if checkbox is checked
if( $(this).attr("checked")=="checked")
于 2013-06-21T10:19:39.257 回答