How To Check Checkbox In Jquery

Checking and unchecking checkboxes using jQuery is a simple task. In this tutorial, we will demonstrate how to
check a checkbox in jQuery and explore some common use cases.

Basic Usage

In order to check a checkbox in jQuery, we can use the
prop() method, which allows us to set a property on the matched elements. To check a checkbox,
simply set the “checked” property to true using the following syntax:

$(‘input[type=”checkbox”]’).prop(‘checked’, true);

In the example above, we selected all checkboxes in the document and set their “checked” property to true,
effectively checking them. To uncheck a checkbox, set the “checked” property to false:

$(‘input[type=”checkbox”]’).prop(‘checked’, false);

Check by ID

If you want to check a specific checkbox by its ID, you can use the same
prop() method and use the ID selector. Let’s say we have a checkbox with the ID
“myCheckbox”, we can check it using the following code:

$(‘#myCheckbox’).prop(‘checked’, true);

Check by Class

Similarly, you can check all checkboxes with a specific class. Let’s say we have multiple checkboxes with the
class “myCheckboxes”, we can check all of them using the following code:

$(‘.myCheckboxes’).prop(‘checked’, true);

Toggle Checkbox

If you want to toggle the checked state of a checkbox, you can use the
prop() method along with a function, like this:

$(‘input[type=”checkbox”]’).prop(‘checked’, function (index, current) {
return !current;
});

In the example above, we used a function to set the “checked” property for each checkbox. The function receives
two arguments: the index of the current element in the collection and its current “checked” property value. We
simply return the negation of the current value, effectively toggling the checked state.

Check by Attribute

You can also check checkboxes with a specific attribute value. For example, let’s say we have multiple
checkboxes with a custom attribute data-type=”myType”. We can check all of them using the following code:

$(‘input[type=”checkbox”][data-type=”myType”]’).prop(‘checked’, true);

Conclusion

In this tutorial, we have demonstrated how to check checkboxes using jQuery. The
prop() method provides an easy way to manipulate the checked state of checkboxes by setting the
“checked” property. You can use it with different selectors to target specific checkboxes or groups of
checkboxes, making it a versatile and powerful tool for handling checkbox interactions.