Author: Steven Neiland
Published:

Warning: This blog entry was written two or more years ago. Therefore, it may contain broken links, out-dated or misleading content, or information that is just plain wrong. Please read on with caution.

A coworker of mine got stung by this last week. While refactoring some logic he needed to reverse a result of a checkbox checked. Knowing that .is() returns a boolean he assumed that .not() would return the inverse.

This is what he was trying to get working, but as you will read on it did not work as expected.

// This does not work as expected var notChecked = $('#somecheckbox').not(':checked'); if(notChecked){ // somelogic } else { // so other logic }

.not() is a filtering function

Per the JQuery .not() documentation the value returned into the notChecked variable was actually a jquery object containing a subset of elements which do not match the checked rule and not a simple boolean.

The opposite of .is() is !.is()

Of course the solution is to simply use the javascript not operator "!" .

// This does work var notChecked = !( $('#somecheckbox').is(':checked') ); if(notChecked){ // somelogic } else { // so other logic }

What Do You Think?

Reader Comments

Commenting has been disabled.

Archives Blog Listing

Tag Listing

Learn CF In A Week

Treehouse

 
Fork me on GitHub