How To Make Checkbox Checked In Jquery

In this blog post, we will learn how to make a checkbox checked using jQuery. We will cover two different methods: using the prop() method and using the attr() method. Let’s dive in!

Using the prop() Method

The prop() method is the most recommended way to set the checked property of a checkbox. This method can be used to either get the property value or set the property value of the selected elements. To make a checkbox checked using the prop() method, you simply need to set the ‘checked’ property to true.

$(document).ready(function() {
    // Make the checkbox with the ID 'myCheckbox' checked
    $('#myCheckbox').prop('checked', true);
});

Using the attr() Method

Another way to make a checkbox checked is by using the attr() method. This method can be used to get or set the attribute value of the selected elements. To make a checkbox checked, you need to set the ‘checked’ attribute to the value ‘checked’.

$(document).ready(function() {
    // Make the checkbox with the ID 'myCheckbox' checked
    $('#myCheckbox').attr('checked', 'checked');
});

It is important to note that using the attr() method for setting the ‘checked’ attribute could cause issues in some scenarios. For instance, when you remove the ‘checked’ attribute using the removeAttr() method, the checkbox might still appear checked in some browsers. Therefore, it is recommended to use the prop() method instead.

Conclusion

In this blog post, we have learned how to make a checkbox checked using jQuery. We covered two methods: prop() and attr(). While both methods can be used to make a checkbox checked, it is recommended to use the prop() method as it provides more consistent results across different browsers.