JS实现全选与取消 Jquery判断checkbox是否被选中

1.JS实现checkbox全选与取消

   <body>

  <input type="checkbox" name="select_all"/>11

      <input type="checkbox" name="select_all"/>22

   <input type="checkbox" name="select_all"/>33

     <input type="checkbox" name="select_all" onClick="selAll(this)">全选

  </body>

     JS代码:

  function selAll(obj)//全选与实现全选取消
  {
      var o=document.getElementsByName("select_all");
      for(var i=0;i<o.length;i++)
      {
          if(obj.checked==true)
             {

      o[i].checked=true;

       } else{
                o[i].checked=false;

      }
         }
    }

2.Jquery判断checkbox是否被选中

  在html的checkbox里,选中的话会有属性checked="checked"。

     如果有一个checkbox被选中,alert这个checkbox属性"checked"的值

  alert($"#xxx".attr("checked")),会打印出"true",而不是"checked"!

  如果没被选中,打印出的是"undefined"。

  if($"#xxx".attr("checked")=="true") //这样是错误的

  jQuery的API手册,attr(name)的返回值是object。所以,应该是 

     if($("#xxx").attr("checked")==true)。

  判断这个值 $("input[name='weibo_count']").attr("checked"); 这样也行

  $("#btn1").click(function(){ 
         $("[name='checkbox']").attr("checked",'true');//全选
     })
   $("#btn2").click(function(){
       $("[name='checkbox']").removeAttr("checked");//取消全选
    })

原文地址:https://www.cnblogs.com/jsingleegg/p/3487049.html