:::: MENU ::::

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

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

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?

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.

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

jQuery code to initialize this plugin

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

Demo using jQuery 2.0.2 where prop() function is available


So, what do you think ?

  •