Stuff & Nonsense

JQuery ‘exists’ and ‘checked’ functionality

One of the brilliant things about jquery is that it’s so easy to extend, whether that be by writing your own full blown plugin, or with a quick 1 liner to add new functionality.

Here’s a couple that I always find handy. First up, adding an ‘exists’ function, so you can do this:

if ($(selector).exists()){
    //do something here if our selected element exists
}

the code is really quite simple, basically we return true if the JQuery object returned by our selector has a length greater than 0 (ie: if the selector matches anything), and false if it doesn’t.

jQuery.fn.exists = function(){
          return jQuery(this).length>0;
}

Next we have something I use all the time, a really simple function that returns true if the checkbox element you call it on is in the ‘checked’ state, and false if it isn’t. So you can do this:

if ('#mycheckbox').checked(){
      //do something here if the checkbox is checked
}

and the code to add that function is:

jQuery.fn.checked = function(){
         return jQuery(this).is(':checked');
}

Hopefully those will be of use to someone else, they’re not particularly complex but they can make your code easier to understand and save you a bit of typing.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.