在 click-jQuery 上检查是否未选中复选框

我想要检查一个复选框是否没有被选中,当用户点击它的时候。这是因为我想在用户取消选中复选框时进行验证。因为至少需要选中一个复选框。所以如果他取消检查最后一个,然后自动检查本身。

使用 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');
});

但是这总是显示“未经检查”的信息。不是我真正期待的..。

Demo: < a href = “ http://jsfiddle.net/tVM5H/”rel = “ norefrer”> http://jsfiddle.net/tvm5h/

所以最终我需要这样的东西:

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

但显然这样不行。我不想使用第一个例子,因为那样我就会有一个不必要的“ else”语句,而我只需要一个“ if”语句。

首先,这是一个 jQuery 错误吗?因为对我来说这是意想不到的行为。其次,有人想到更好的选择吗?

317784 次浏览

Try this:

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

demo

jQuery to check for checked? Really?

if(!this.checked) {

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

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)

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.

Do it like this

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


// To check if checkbox is checked
if( $(this).attr("checked")=="checked")

The Answer already posted .But We can use the jquery in this way also

demo

$(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');
});
});
$(document).ready(function() {
$("#check1").click(function() {
var checked = $(this).is(':checked');
if (checked) {
alert('checked');
} else {
alert('unchecked');
}
});
});
<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>

Code taken from here : http://chandreshrana.blogspot.in/2015/10/how-to-check-if-checkbox-is-checked-or.html