编程语言
首页 > 编程语言> > JavaScript CheckBox实现全选和部分选择

JavaScript CheckBox实现全选和部分选择

作者:互联网

 1 <html>
 2 <head>
 3     <script>
 4         function BatchAddToBasket() {
 5             var questionNums = '';
 6             var checkboxs = document.getElementsByName('question');
 7             for (var i = 0; i < checkboxs.length; i++) {
 8                 var isChecked = false;
 9                 if (checkboxs[i].checked) {
10                     isChecked = true;
11                     break;
12                 }
13             }
14             if (!isChecked) {
15                 alert('请至少选择一个选项');
16                 return;
17             }
18 
19             for (var i = 0; i < checkboxs.length; i++) {
20                 if (checkboxs[i].checked) {
21                     questionNums += checkboxs[i].id;
22                     if (i < checkboxs.length - 1) 
23                     questionNums += ',';
24                 }
25             }
26             alert('选项id:' + questionNums);
27         }
28 
29         function SelectAll(obj) {
30             if (obj.checked) {
31                 var checkboxs = document.getElementsByName('question');
32                 for (var i = 0; i < checkboxs.length; i++) {
33                     checkboxs[i].checked = true;
34                 }
35             } else {
36                 var checkboxs = document.getElementsByName('question');
37                 for (var i = 0; i < checkboxs.length; i++) {
38                     checkboxs[i].checked = false;
39                 }
40             }
41         }
42     </script>
43 </head>
44 <body>
45     <div>
46         <input type="checkbox" name="checkboxAll" onclick="SelectAll(this)">
47         <button onclick="BatchAddToBasket()">加入试题篮</button>
48     </div>
49     <div>
50         <input type="checkbox" name="question" id=0>
51         <input type="checkbox" name="question" id=1>
52         <input type="checkbox" name="question" id=2>
53     </div>
54 </body>
55 </html>

 

标签:CheckBox,checked,++,JavaScript,length,全选,var,questionNums,checkboxs
来源: https://www.cnblogs.com/yaosj/p/10341275.html