zoukankan      html  css  js  c++  java
  • jQuery实现checkbox选项组全选,全不选,获取checkbox选项组的值

    1.创建checkbox选项组

    https://www.cnblogs.com/YorkZhangYang/p/12587827.html

     1.1checkbox选中状态通过checked属性判断,true为选中状态,false为取消选中状态

    <input type="checkbox"  name="fruits"  value="苹果" checked="true">

    1.2jQuery判断checkbox状态方法

    prop()方法

     console.log($("input[name='fruits']:checkbox").prop("checked"));   

    is()方法

    console.log($("input[name='fruits']:checkbox").is(":checked"));  

    1.3设置选中,取消选中

    $("input[name='fruits']:checkbox").attr('checked',true);
    $("input[name='fruits']:checkbox").attr('checked',false);

    $("input[name='fruits']:checkbox").prop('checked',true);
    $("input[name='fruits']:checkbox").prop('checked',false);

    2.实现全选、全不选功能

       <script>
          $(function(){ 
              //单击全选框选中所有checkbox
          $("#checkAll").click(function(){
            if(this.checked)
            {
                 $("input[type=checkbox]").prop("checked", true);
                //$("input[name='fruits']:checkbox").attr("checked",true);//使用attr方法第二次单击无法全选
            }
            else{
                $("input[name='fruits']").each(function(){
                    $(this).prop("checked",false);
                });
            }  
          });      
          });
       </script>

    3.获取checkbox的值

      //获取未选中checkbox的值
          var checkedList1 = new Array();
          $("input[type='checkbox']:not(:checked)").each(function(){
            checkedList1.push($(this).val());
          });
          //控制台输出
          checkedList1.forEach(function(val,index){console.log(val,index)});
    
       //获取已选中checkbox的值
        var checkedList2 = new Array();
          $("input[type='checkbox']:checked").each(function(){
            checkedList2.push($(this).val());
          });
          //控制台输出
          checkedList2.forEach(function(val,index){console.log(val,index)});
          });

    4.效果图

    注意:尽量不要用attr方法增加属性,否则会出现再次点击不生效的情况,用prop方法较好。

    参考文章:

    https://www.cnblogs.com/wangluochong/p/5579056.html

    https://www.w3h5.com/post/109.html

    https://blog.csdn.net/qq_32973061/article/details/81749906

    https://blog.csdn.net/u011637069/article/details/51290164

     console.log($("input[name='fruits']:checkbox").prop("checked"));   
    转载文章链接已标明,如有侵权请告知。文章仅作为知识记忆所用,如有错误,敬请指正。
  • 相关阅读:
    [转载]qemu-kvm安装配置
    Hadoop通过c语言API访问hdfs
    hadoop和hdfs环境搭建
    OpenCV installation for Ubuntu 12.04
    homework-01
    linux命令2
    压缩tar
    anaconda 安装opencv
    anconda安装第三方库
    开源代码
  • 原文地址:https://www.cnblogs.com/YorkZhangYang/p/12587155.html
Copyright © 2011-2022 走看看