📌  相关文章
📜  jquery 设置复选框已选中 - Javascript (1)

📅  最后修改于: 2023-12-03 15:16:50.110000             🧑  作者: Mango

Introduction to setting checkbox as checked using jQuery

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.

HTML Markup

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>
jQuery Code

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.

Conclusion

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.