<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>表单操作-复选框</title> <style> *{margin:0; padding: 0;} li{list-style: none;} .clearfix:before,.clearfix:after{display: table; content: "";} .clearfix:after{clear: both; overflow: hidden;} .clearfix{zoom:1;} .f-fl{float: left;} .f-mr20{ margin-right: 20px;} fieldset{margin:50px auto; width: 1000px; padding: 20px; border: 0; color:#333;} #form dt{padding:15px 0 5px;} #form p{ margin-bottom: 10px;} #form p input[type=checkbox]{ margin-right: 5px;} #form dd p{padding-left:30px;} </style> <script type="text/javascript" src="http://code.jquery.com/jquery-1.8.1.js"></script> <script type="text/javascript"> $(document).ready(function(){ var txt = $('fieldset').find('legend').text(); $('fieldset').find('legend') .replaceWith('<h2>'+ txt +'</h2>').css('backgroundColor','green'); $('#form').on('click','#chkAll',function(){ var flag = this.checked; $('input[name=items]:checkbox').attr('checked',flag); }).on('click','#chkRev',function(){ // 逐个遍历 $('input[name=items]:checkbox').each(function(){ this.checked = !this.checked; }); }).on('click','#send',function(e){ var str = "你选择的兴趣有:\r\n"; $('input[name=items]:checked').each(function(){ str += $(this).val() + "\r\n"; }); alert(str); e.preventDefault(); }).find('input[name=items]:checkbox').bind('click',function(){ // 联动,判断全选按钮是否勾选 var flag = true; $('input[name=items]:checkbox').each(function(){ if(!this.checked){ flag = false; } }); $('#chkAll').prop('checked',flag); });; }); </script> </head> <body> <fieldset> <legend>你的爱好是?</legend> <form action="post" id="form"> <dl> <dt><p><span class="f-mr20"><input type="checkbox" name="" id="chkAll">全选</span><input type="checkbox" name="" id="chkRev">反选</p></dt> <dd> <p><input type="checkbox" name="items" id="" value="足球" />足球</p> <p><input type="checkbox" name="items" id="" value="篮球" />篮球</p> <p><input type="checkbox" name="items" id="" value="网球" />网球</p> <p><input type="checkbox" name="items" id="" value="羽毛球" />羽毛球</p> <p><input type="checkbox" name="items" id="" value="桌球" />桌球</p> <p><input type="submit" id="send" value="提交"></p> </dd> </dl> </form> </fieldset> </body> </html>
原文地址:http://blog.csdn.net/ruizhengyun/article/details/28477481