最近做项目时需要使用jquery做全选功能,总结记录如下:
1 | <div class="check"> |
2 | <label> |
3 | <input type="checkbox" name="all" onchange="selectAll(this)">全选 |
4 | </label> |
5 | <label> |
6 | <input type="checkbox" value="" name="check_1" class="check_input" onchange="change(this)">1 |
7 | </label> |
8 | <label> |
9 | <input type="checkbox" value="" name="check_2" |
10 | class="check_input"onchange="change(this)">2 |
11 | </label> |
12 | <label> |
13 | <input type="checkbox" value="" name="check_3" class="check_input" onchange="change(this)">3 |
14 | </label> |
15 | </div> |
js 代码如下:
1 | function selectAll(obj){ |
2 | if($(obj).is(':checked')) { |
3 | $(obj).parents('.check').find("input[name^=check_]").prop("checked","true"); |
4 | }else{ |
5 | $(obj).parents('.check').find("input[name^=check_]").removeAttr("checked") |
6 | } |
7 | } |
8 | function change(bom) { |
9 | if($(bom).is(":checked")){ |
10 | if($('input[name^=check_]:checked').length == $('.check_input').length){ |
11 | $('.check input[name=all]').prop("checked","true"); |
12 | }else{ |
13 | $('.check input[name=all]').removeAttr("checked"); |
14 | } |
15 | }else{ |
16 | $('.check input[name=all]').removeAttr("checked"); |
17 | } |
18 | } |