Home > Article > Web Front-end > Use jQuery to implement real-time updates of checkbox selected status
Use jQuery to implement real-time updates of the selected status of check boxes
In web development, we often encounter situations where we need to update the selected status of check boxes in real time. . By using jQuery, we can easily implement the function of updating the selected status of the check box in real time. Here's how to use jQuery to accomplish this task.
First, we need to prepare a simple HTML structure containing multiple check boxes:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>复选框选中状态实时更新</title> <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script> </head> <body> <label><input type="checkbox" class="checkbox"> 选项1</label> <label><input type="checkbox" class="checkbox"> 选项2</label> <label><input type="checkbox" class="checkbox"> 选项3</label> <script> // 使用jQuery来实现复选框选中状态的实时更新 $('.checkbox').change(function() { if ($(this).is(":checked")) { console.log("选中了复选框:" + $(this).parent().text()); } else { console.log("取消选中复选框:" + $(this).parent().text()); } }); </script> </body> </html>
In the above code, we use the jQuery library and define three check boxes frame. By adding a change event listener, when the status of the check box changes, the corresponding callback function will be triggered. In the callback function, we can perform corresponding operations based on the selected state of the check box. Here we simply output a message to the console.
Run the above code. When we check or uncheck any check box, we will see the corresponding prompt information in the console, which realizes real-time updating of the checked status of the check box. Function.
Through this simple example, we can see that real-time updating of the checked status of the check box can be easily achieved using jQuery. In practical applications, we can expand functions according to specific needs, such as submitting the selected check box information to the server or displaying it on the page. Hope this example helps you.
The above is the detailed content of Use jQuery to implement real-time updates of checkbox selected status. For more information, please follow other related articles on the PHP Chinese website!