📅  最后修改于: 2023-12-03 15:16:50.110000             🧑  作者: Mango
Setting a checkbox as checked or unchecked using jQuery is a common requirement in web development. In this tutorial, we will learn how to use jQuery to set the checkbox as checked or unchecked.
To demonstrate how to use jQuery to set a checkbox as checked or unchecked, we will create a simple HTML form with checkboxes.
<form>
<fieldset>
<legend>Select your favourite fruits</legend>
<input type="checkbox" name="fruit[]" value="Apple"> Apple<br>
<input type="checkbox" name="fruit[]" value="Banana"> Banana<br>
<input type="checkbox" name="fruit[]" value="Cherry"> Cherry<br>
</fieldset>
</form>
We can use the prop
method in jQuery to set the checked
property of a checkbox. Here is the jQuery code to set the first checkbox as checked.
$(document).ready(function() {
$('input[name="fruit[]"][value="Apple"]').prop("checked",true);
});
In this code, we use the $(document).ready()
function to make sure the HTML document is loaded before we execute the code. Then we use the selector $('input[name="fruit[]"][value="Apple"]')
to select the first checkbox with the value Apple
. Finally, we use the prop
method to set the checked
property of the checkbox to true
.
Using the prop
method in jQuery, we can set the checked
property of a checkbox to either true
or false
. This is a simple and effective way to manipulate checkboxes on a web page using jQuery.