玩转复选框,全选,反选,全不选,获取选中的值

版权声明:俗世凡人行(释) QQ:748507607 https://blog.csdn.net/weixin_41887155/article/details/88728489
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>复选框</title>
</head>
<body>
      兴趣爱好:
      <input type="checkbox" name="category" value="1" />财经   
      <input type="checkbox" name="category" value="2" />汽车    
      <input type="checkbox" name="category" value="3" />科技   
      <input type="checkbox" name="category" value="4" />房产   
      <input type="checkbox" name="category" value="5" />旅游 
      <p>
          <button id="quanxuan">全选</button>  
          <button id="quanbuxuan">全不选</button>  
          <button id="getValue">获取选中的值</button>  
          <button id="jishu">选中奇数</button>  
          <button id="oushu">选中偶数</button>  
          <button id="fanxuan">反选</button>  
      </p>
</body>
</html>

<script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
<script type="text/javascript">
    //全选
    $("#quanxuan").click(function(){
      $("input[name='category']").attr("checked","true"); 
    });
    //全不选
    $("#quanbuxuan").click(function(){
      $("input[name='category']").removeAttr("checked"); 
    });
    //获取复选框的值并拼接成字符串,逗号分开
    $("#getValue").click(function(){
      var checkname = "";
      $("input[name='category']:checkbox:checked").each(function(){
         checkname+=$(this).val()+",";
      }) 
      alert(checkname);
    });
    //选中所有奇数
    $("#jishu").click(function(){
      $("input[name='category']:odd").attr("checked","true"); 
    });
    //选中所有偶数
    $("#oushu").click(function(){
      $("input[name='category']:even").attr("checked","true"); 
    });
    //反
    $("#fanxuan").click(function(){     
      $("input[name='category']").each(function(){ 
        $(this).prop("checked",!$(this).prop("checked"));
      })       
    });
</script>

猜你喜欢

转载自blog.csdn.net/weixin_41887155/article/details/88728489
今日推荐