检查单击时是否未选中复选框-jQuery [英] Check if checkbox is NOT checked on click - jQuery

查看:64
本文介绍了检查单击时是否未选中复选框-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');
});

但这将始终显示未选中"消息.并不是我所期望的...

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

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

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

但是显然这是行不通的.我不想使用第一个示例,因为那样的话,当我只需要一个'if'语句时,就会有一个不必要的'else'语句.

那么第一件事,这是一个jQuery错误吗?对我来说,这是意外的行为.其次,任何人都有理想的替代品吗?

解决方案

尝试一下:

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

演示

I want to check if a checkbox just got unchecked, when a user clicks on it. The reason for this is because i want to do a validation when a user unchecks a checkbox. Because atleast one checkbox needs to be checked. So if he unchecks the last one, then it automatically checks itself again.

With jQuery i can easily find out wether it's checked or not:

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

But i actually only want to have an if statement that checks if a checkbox just got unchecked.

So i thought i could do that with the following code:

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

But this will always show the 'unchecked' message. Not really what i was expecting...

demo: http://jsfiddle.net/tVM5H/

So eventually i need something like:

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

But obviously this doesn't work. I rather don't want to use the first example, because then i'd have an unnecessary 'else' statement when i only need one 'if' statement.

So first thing, is this a jQuery bug? Cause to me it's unexpected behaviour. And second, anyone any ides for a good alternative?

解决方案

Try this:

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

demo

这篇关于检查单击时是否未选中复选框-jQuery的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆