检查是否复选框未被选中

编程入门 行业动态 更新时间:2024-10-22 16:27:14
检查是否复选框未被选中 - jQuery(Check if checkbox is NOT checked on 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'); });

但是这将始终显示“未选中”的消息。 不是真的我期待的...

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

所以最终我需要像:

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

但显然这不行。 我宁愿不想使用第一个例子,因为当我只需要一个'if'语句时,我会有一个不必要的'else'语句。

那么第一件事,这是一个jQuery的bug? 对我来说这是意想不到的行为。 第二,任何人都有一个很好的选择吗?

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?

最满意答案

尝试这个:

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

演示

Try this:

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

demo

更多推荐

jQuery,So,want,电脑培训,计算机培训,IT培训"/> <meta name="description&qu

本文发布于:2023-07-31 01:32:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1340482.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:未被   复选框

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!