Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if checkbox is NOT checked on click - jQuery

Tags:

jquery

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?

like image 692
w00 Avatar asked Jun 22 '12 15:06

w00


People also ask

How do you check if checkbox is checked or not?

Checking if a checkbox is checked First, select the checkbox using a DOM method such as getElementById() or querySelector() . Then, access the checked property of the checkbox element. If its checked property is true , then the checkbox is checked; otherwise, it is not.

How do you check if all checkboxes are checked in jQuery?

So the correct code is: $('input. abc'). not(':checked'). length === 0 .


1 Answers

Try this:

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

demo

like image 187
antyrat Avatar answered Oct 14 '22 13:10

antyrat