Many times we need to show or hide an element based on the current state of a checkbox and for that we should first check whether the checkbox is checked or not.
This article will explain three methods by which you can determine whether the checkbox is checked or not using jQuery and javascript both.
Select the checkbox using its id or class and then use jQuery’s
:checked
selector along with is
function to know its checked value.If is function returns
true
, then the checkbox is checked and if it returns false
then the checkbox is not checked. Example,<input id="dummy" checked="checked" type="checkbox" /> <script> if($("#dummy").is(":checked") { console.log("Checked"); } else { console.log("Not checked"); } </script>
Above code when executed will print Checked on the console.
:checked
selector returns all the checkboxes that are checked on the current page. When a particular checkbox is selected using its id and :checked
is placed inside is
function, then its checked state is returned.
Learn different ways of selecting an element in jQuery here.
Using prop method in jQuery
prop
method takes a property name as argument and returns the value of that property for an element. Pass the checked
property of the checkbox as an argument to this method and it will return its value.checked
property will be true
if the checkbox is in checked state and false
if the checkbox is not checked. Example, <input id="dummy" checked="checked" type="checkbox" /> <script> if($("#dummy").prop("checked") { console.log("Checked"); } else { console.log("Not checked"); } </script>
Remember that first you need to select the checkbox using its selector(id, in this case).
Use the
checked
property of an HTML element to know if a checkbox is checked or not. Select an element using document
object in javascript and then use its checked
property to get the checked value of the checkbox.This property returns
true
if the element is checked, false
otherwise. Example, <input id="dummy" type="checkbox" /> <script> if(document.getElementById("dummy").checked) { console.log("Checked"); } else { console.log("Not checked"); } </script>
Above example uses getElementById
method of document
object to select the checkbox by its id and then its checked
property is used to determine if it is checked.
This example will print Not checked at the console since the checkbox is not checked or not.