Today's Question:  What's your opinion about Alibaba mooncake incident?        GIVE A SHOUT

Technical Article => Web =>  JavaScript

jQuery to check whether checkbox is checked

  Pi Ke      2015-07-25 08:49:54      2,569    0    1

In Vanilla JavaScript, the correct way of checking whether a checkbox is checked is to get the property checked of the checkbox. Assuming there is an checkbox with id "checkbox1", below line will return true if the checkbox is checked while it will return false if the checkbox is unchecked:


In jQuery, there are a few ways to check this. The first one is to using the corresponding counterpart of the Vanilla JavaScript, it is to check the checked property.


The prop() method will get the value of a property for the first element in the set of matched elements. Here in this case it's the checked value.

Prior to jQuery 1.9, the attr() method can be used to get the attribute value of checked. But what it returns may not be true or false. If the checked is defined, the return value will be "checked", otherwise the value will be "undefined". After jQuery 1.6, the attr() method is not recommended to get or set the value of boolean attributes such as checked and disabled. Instead, you should use prop() method in the future.

The second method is to call the is() method and then check the :checked selector.


The :checked selector will match all elements that are checked or selected. It works for checkboxes, radio buttons, and select elements.  The is() method will check the current matched set of elements against a selector, element, or jQuery object and return true if at least one of these elements matches the given arguments.

The third method is to get the value of element with :checked selector. If the value is not undefined, then it is checked, otherwise it is unchecked.

$("#checkbox1:checked").val() != undefined

Note you CANNOT use below line to check whether the checkbox is checked:


If the checkbox has set its value attribute to empty string(""), since empty string will be evaluated to false, so the above line will not work if the checkbox has the value set to empty.



Share on Facebook  Share on Twitter  Share on Google+  Share on Weibo  Share on Reddit  Share on Digg  Share on Tumblr    Delicious



No comment for this article.


When unexpected behavior occurs

By sonic0002