JQuery遍历CheckBox踩坑记

 

$("#checkbox_id").attr("checked"); //获取一个CheckBox的状态(有没有被选中,返回true/false) 

$("#checkbox_id").prop("checked"); (推荐)

$("#checkbox_id").attr("checked",true); //设置一个CheckBox的状态为选中(checked=true)

$("#checkbox_id").prop("checked",true);  (推荐)

有的同学在用$("#checkbox_id").attr("checked");  这个属性的时候返回的是undefined 或者是checked因为

如果使用attr方法获取时,如果当前input中初始化未定义checked属性,则不管当前是否选中,$("#checkbox_id").attr("checked")都会返回undefined; 

所以 如果使用jquery,最好应使用prop方法来获取和设置checked属性,不应使用attr

遍历代码:

 1 function select_checkbox() {
 2     var flag = 0;
 3 
 4     $("input[name='m']:checkbox").each(function () {
 5         if ($(this).prop("checked")) {
 6             console.log($(this).parent().text());
 7             flag += 1;
 8         }
 9     });
10     if (flag < 1) {
11         alert("至少要选中一个!");
12     }
13 
14 }

参考:http://www.cnblogs.com/huangqing/articles/2226604.html

   http://www.jb51.net/article/50396.htm

原文地址:https://www.cnblogs.com/eoooxy/p/6268646.html