jQuery 之玩转 checkbox

<!DOCTYPE html>
<html>

<head>
    <title></title>
    <meta charset="utf-8">
    <script type="text/javascript" src='http:cdn.bootcss.com/jquery/3.1.1/jquery.min.js'></script>
</head>

<body>
    <form>
        <input type="checkbox" class="all"> 全选
        <input type="checkbox" class="reverse"> 反选
        <input type="checkbox" value="1" class="sub"> 1
        <input type="checkbox" value="2" class="sub"> 2
        <input type="checkbox" value="3" class="sub"> 3
        <input type="checkbox" value="4" class="sub"> 4
        
        

        <input type="button" value="click">
        <input type="reset">
    </form>
    <script type="text/javascript">
    $(function() {
        $('.all').on('click', function(e) {
            var isChecked = $(this).prop("checked");
            $(".sub").prop("checked", isChecked);
        })

        $('.reverse').on('click', function(e) {
            $(".sub").each(function(index, ele) {
                var checked = $(ele).is(':checked') ? '' : 'checked'
                $(ele).prop("checked", checked);
            })
        })

        $('.sub').on('click', function(e) {
            var checked = ($('.sub').length == $('.sub:checked').length ? 'checked' : '')
            $('.all').prop('checked', checked)
        })

        $("input[type='button']").bind('click',function(){
            var obj = $('.sub').map(function(index,ele){
                return $(ele).val()
            })
            var arr = Array.prototype.slice.call(obj)
            alert(JSON.stringify(arr))
        })
    })
    </script>
</body>

</html>

 

posted @ 2016-12-29 12:06  JonasYu  阅读(148)  评论(0编辑  收藏  举报