一個checkbox 用jquery實現全選、全不選


之前因為一個很小的錯誤弄了很久,現在才做好。

效果圖:

肯定還有更簡單的方法。

 1 <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Checkbox.aspx.cs" Inherits="WebApp.Test.Checkbox" %>
 2 
 3 <!DOCTYPE html>
 4 
 5 <html xmlns="http://www.w3.org/1999/xhtml">
 6 <head runat="server">
 7     <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 8     <title></title>
 9     <script src="../Scripts/jquery-1.8.0.min.js"></script>
10     <script type="text/javascript">
11         $(function () {
12             jQueryCheckAll();
13         })
14         function jQueryCheckAll() {
15             var checkAll = $('#checkedAll');
16             var items = $(':checkbox[name=item]');
17            
18             checkAll.click(function () {
19                 if ($(this).attr('checked')) {
20                     items.each(function () {
21                         $(this).attr('checked', true);
22                     })                  
23                 }
24                 else {
25                     items.each(function () {
26                         $(this).attr('checked', false);
27                     })
28                 }
29                 items.click(function () {
30                     checkAll.attr("checked", items.length == $(':checkbox[name=item]:checked').length ? true : false);
31                 });
32             })      
33         }      
34     </script>
35 </head>
36 <body>
37     <form id="form1" runat="server">
38         <div>
39             你愛好的運動是?
40             <input type="checkbox" id="checkedAll"/>全選/全不選<br/>
41             <input type="checkbox" name="item" value="足球" />足球
42             <input type="checkbox" name="item" value="籃球" />籃球
43             <input type="checkbox" name="item" value="羽毛球" />羽毛球
44             <input type="checkbox" name="item" value="乒乓球" />乒乓球
45         </div>
46     </form>
47 </body>
48 </html>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM