skip to Main Content

Setting "checked" for a checkbox with jQuery

To set the checked state of a checkbox using jQuery, you can use the prop() method. Here’s an example:

HTML:

<input type="checkbox" id="myCheckbox">
<label for="myCheckbox">Check me</label>

JavaScript (jQuery):

// Set the checkbox as checked
$('#myCheckbox').prop('checked', true);

// Set the checkbox as unchecked
$('#myCheckbox').prop('checked', false);

// Toggle the checkbox state
$('#myCheckbox').prop('checked', function(_, currentVal) {
  return !currentVal;
});

In this example, the prop() method is used to manipulate the checked property of the checkbox with the ID myCheckbox. By passing true or false as the second argument to prop(), you can set the checkbox state accordingly.

You can also use a function as the second argument of prop(), which allows you to toggle the checkbox state. The current value of the checked property is passed as the second parameter to the function, and the function should return the new value you want to set.

These examples demonstrate how to set the checked state of a checkbox using jQuery’s prop() method.

A Self Motivated Web Developer Who Loves To Play With Codes...

This Post Has 0 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

Back To Top