jQuery複選框實現全選、全不選、反選、獲取選項值
阿新 • • 發佈:2018-12-24
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>複選框</title> <script src="../js/jquery-3.1.1.js"></script> <script> $(document).ready(function(){ //全選/全不選 $("#selectAll").change(function(){ $("input[name='items']").prop("checked",this.checked); }); //全選 $("#checkedAll").click(function(){ $("input[name='items']").prop("checked",true); }); //全不選 $("#checkedNo").click(function(){ $("input[name='items']").prop("checked",false); }); //反選 $("#checkRev").click(function(){ $("input[name='items']").each(function(){ this.checked=!this.checked; }); }); //獲得選項的值 $("#checkValue").click(function(){ var result=""; $("input[name='items']").each(function(){ if(this.checked){ result+=$(this).val()+"\n"; } }); alert(result); }); }); </script> <style> .container { margin: 0px auto; width: 500px; } </style> </head> <body> <div class="container"> <label>你愛好的運動是?</label> <p> <input type="checkbox" name="items" value="足球" />足球 <input type="checkbox" name="items" value="籃球" />籃球 <input type="checkbox" name="items" value="排球" />排球 <input type="checkbox" name="items" value="檯球" />檯球 </p> <p> <input type="checkbox" id="selectAll" value="0" />全選 <input type="button" id="checkedAll" value="全選" /> <input type="button" id="checkedNo" value="全不選" /> <input type="button" id="checkRev" value="反選" /> <input type="button" name="name" id="checkValue" value="獲得選中值" /> <input type="button" id="submit" value="提交" /> </p> </div> </body> </html>