Today's Question:  What does your personal desk look like?        GIVE A SHOUT

jQuery to check whether checkbox is checked

  Pi Ke        2015-07-25 08:49:54       15,227        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:

document.getElementById("checkbox1").checked

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.

$("#checkbox1").prop("checked")

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.

$("#checkbox1").is(":checked")

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:

$("#checkbox1:checked").val()?true:false

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.

JQUERY  CHECKBOX  CHECKED  ATTR  PROP 

Share on Facebook  Share on Twitter  Share on Weibo  Share on Reddit 

  RELATED


  1 COMMENT


Anonymous [Reply]@ 2018-06-22 05:28:40

ttttt