To check a checkbox using jQuery, you can use the prop() method to set the checked property to true. Here’s an example:
HTML code:
<input type="checkbox" id="myCheckbox">
<label for="myCheckbox">Check me</label>
jQuery code:
$(document).ready(function() { $('#myCheckbox').prop('checked', true); });
In the code above, the prop() method is used to set the checked property of the checkbox with the ID myCheckbox to true. You can replace true with false to uncheck the checkbox.
Note that the above code assumes that you have included the jQuery library in your HTML file. If you haven’t done so, you can add the following script tag before the jQuery code:
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
This will include the jQuery library from a CDN (Content Delivery Network).
Key Takeaways
- To check a checkbox using jQuery, you can use the prop() method to set the checked property to true.
- The prop() method is used to get or set the property of an HTML element.
- The checked property is a boolean property that indicates whether the checkbox is checked or not.
- You can use the jQuery selector to select the checkbox by its ID.
- You can use the ready() method to execute the code after the DOM is ready.
FAQ
- What is the jQuery prop() method?
- The prop() method is used to get or set the property of an HTML element. The syntax is:
$(element).prop(‘property’, value);
where element is the jQuery selector for the element, property is the name of the property, and value is the new value of the property.
- What is the checked property?
- The checked property is a boolean property that indicates whether the checkbox is checked or not. The value of the checked property can be either true or false.
- How do I select a checkbox by its ID using jQuery?
- You can use the jQuery selector to select the checkbox by its ID. The syntax is:
$(‘input[id=”myCheckbox”]’);
where myCheckbox is the ID of the checkbox.
- What is the ready() method?
- The ready() method is used to execute the code after the DOM is ready. This means that the code will not be executed until the HTML document has been loaded and parsed.