jquery处理checkbox(复选框)是否被选中实例代码

jquery处理checkbox(复选框)是否被选中

现在如果一个复选框被选中,是用checked=true,checked="checked"也行

要用prop代替attr会更好,虽然在jQuery1.6之前版本的attr()方法能正常使用,但是现在必须使用prop()方法代替

实例代码:

<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"/> <title>checkbox</title> </head> <body> <input type="button" value="全选"> <input type="button" value="取消全选"> <input type="button" value="选中所有奇数"> <input type="button" value="反选"> <input type="button" value="获得选中的所有值"> <input type="checkbox" value="checkbox1"/> <input type="checkbox" value="checkbox2"/> <input type="checkbox" value="checkbox3"/> <input type="checkbox" value="checkbox4"/> <input type="checkbox" value="checkbox5"/> <script src="https://www.jb51.net/js/jquery-3.2.0.min.js"></script> <script> $(function(){ var checkbox = $("input[type=checkbox]"); $("#btn1").on("click",function(){ checkbox.prop("checked",true); }); $("#btn2").on("click",function(){ checkbox.prop("checked",false); }); $("#btn3").on("click",function(){ $("input[type=checkbox]:even").prop("checked",true); }); $("#btn4").on("click",function(){ checkbox.each(function(){ if($(this).prop("checked")){ $(this).prop("checked",false); }else{ $(this).prop("checked",true); } }); }); $("#btn5").on("click",function(){ var str = ""; $("input[type=checkbox]").each(function(){ if($(this).prop("checked")){ str += $(this).val() + ","; } }); console.log(str); }); }); </script> </body> </html>

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wyxdzz.html