您的位置:首页 > 其它

checkbox全选 全不选 所有的子项选中或者不全选中后,全选按钮也选中或者不选中

2015-03-13 17:28 411 查看
1,jsp 页面

 <body>

      <input type="checkbox"  id="selectAll" >全选</br>

      </br>

     <input type="checkbox"  id="sid1">苹果</br>

     <input type="checkbox"  id="sid2">草莓</br>

     <input type="checkbox"  id="sid3">西瓜</br>

     <input type="checkbox"  id="sid4">菠萝</br>

  </body>

2,js

<script>

    $(function(){

        //全选和全不选

        $('#selectAll').bind('click',function(){

        //    alert(this.checked);//选中的时候返回true

            //alert(this);//object HTMLInputElement

            //alert($(this));//object Object

            //alert($(this).prop('checked'));//true

            //alert($(this).attr('checked'));//undefined

            if(this.checked){    //全选

                $("input[id^='sid']").each(function(){

                        $(this).prop('checked',true);

                    })

                }else{    //全不选

                    $("input[id^='sid']").each(function(){

                        $(this).prop('checked',false);

                    })

                    }

            });

        //所有的子项选中或者不全选中后,全选按钮也选中或者不选中

  var allLength=$("input[id^=sid]").length; //所有的checkbox的长度

        $("input[id^=sid]").each(function(){

            $(this).bind('click',function(){

                var selectedLength=$("input[id^=sid]:checked").length;//所有的选中的checkbox的长度

                if(selectedLength==allLength){

                    $('#selectAll').prop("checked",true);//全选按钮

                    }else{

                        $('#selectAll').prop("checked",false);

                        }

            

                })

                

            })

        })

        

    </script>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐