How to know if HTML checkbox is checked in any version of jQuery

Many plugin developers face the difficulties, when core library upgrades and needs plugin code migration. Whenever new version release with big code changes, old version became obstacle with the new version. That doesn’t mean developer start coding for latest version and ignore the old versions. Since these libraries are globally accepted it might be possible some people wouldn’t migrate their libraries due to several reasons. May be, they want to support older browsers or may be their system doesn’t support latest release.

checkbox

Simple answer is

jQuery("input[type='checkbox']").is(":checked");

However, jQuery 1.6 introduced .prop() function which can be used for of .attr() function.

attr() function should be used to retrieve visible attributes like i.e. type, value, href etc

prop() function should be used to retrive DOMs’ internal properties like nodeName, nodeType, selectedIndex etc

We’ll see how to use attr() and prop() both function gracefully if they are available to included jQuery with current document.

How to check if function available in jQuery

if ("func" in jQuery) {
    // your code here
}

so if user is using jQuery >= 1.6 we can detect and availability of function and use it in more efficient way.

Checking if prop function is available in jQuery or not?

if ("prop" in jQuery(this)) {
    // your code here
}

So, if prop is available we can easily check if ( $( elem ).prop( “checked” ) ) within the condition. Incase it’s not available, we try for attr function the same way.

if ("attr" in jQuery(this)) {
    // your code here
}

So, final jQuery function for checking if element is checked or not

 jQuery.fn.isChecked = function () {

        if ("prop" in jQuery(this)) {
            return jQuery(this).prop('checked') == true ? true : false;

        }
        if ("attr" in jQuery(this)) {
            return jQuery(this).attr('checked') == true ? true : false;
        }
        return jQuery(this).is(":checked") == true ? true : false;
    };

jQuery code to initialize this plugin

jQuery(document).ready(function () {
        $('#red_btn').click(function () {
            if ($('#coloropt1').isChecked()) {
                alert("Yes");
            } else {
                alert("No");
            }
        });

Demo using jQuery 1.2.6 where prop() function is not available

Demo using jQuery 2.0.2 where prop() function is available

Total
0
Shares
Leave a Reply

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

 
Previous Post

PHP – Import DigitalAccessPass existing users into vbulletin 5 connect for auto-login

Next Post

Object doesn’t support property or method ‘indexOf’ in IE 8 – Fix

Related Posts