How to Test If a Checkbox is Checked with jQuery

Checkboxes are a fundamental aspect of many web applications, as they allow users to select multiple options from a list.

In this Javascript tutorial, we will learn how to test if a checkbox is checked or not with jQuery.


The Checkbox Element

A checkbox is a form element that allows the user to select one or more options from a list.

It is represented by the <input> tag with a “type” attribute set to “checkbox.” A checkbox can be in two states: checked or unchecked.

When the user checks a checkbox, its state changes from unchecked to checked, and when the user unchecks it, its state changes from checked to unchecked.

jQuery to Test If a Checkbox is Checked

jQuery is a fast, small, and feature-rich JavaScript library.

It makes things like HTML document traversal and manipulation, event handling, and animation much simpler with an easy-to-use API that works across a multitude of browsers.

We can use jQuery to test if a checkbox is checked by using the “:checked” selector.

The “:checked” selector returns all checked checkboxes within a specified context.

Code Example: Let’s consider the following HTML code, which contains three checkboxes.

<form>
  <input type="checkbox" name="vehicle" value="Bike"> I have a bike<br>
  <input type="checkbox" name="vehicle" value="Car"> I have a car<br>
  <input type="checkbox" name="vehicle" value="Boat"> I have a boat<br>
</form>

We can test if a checkbox is checked by using the following jQuery code.

if ($('input[name="vehicle"]:checked').val() === "Bike") {
  alert("You have a bike");
}

In this example, we use the “input[name=’vehicle’]:checked” selector to select the checked checkbox with the name “vehicle.”

The “val()” method is used to get the value of the selected checkbox.

If the value of the selected checkbox is “Bike,” an alert message is displayed.


Conclusion

In this article, we learned how to test if a checkbox is checked or not with jQuery.

By using the “:checked” selector, we can easily select all checked checkboxes within a specified context.

With the help of the “val()” method, we can get the value of the selected checkbox.

By combining these two methods, we can test if a checkbox is checked and take action based on its state.