layui 的checkbox事件

魏鹤轩
2023-12-01
<form class="layui-form"> <!-- 提示:如果你不想用form,你可以换成div等任何一个普通元素 -->
    <div class="layui-form-item">
        <label class="layui-form-label">复选框</label>
        <div class="layui-input-block all" >
            <input type="checkbox" name="like[all]" title="全部" lay-filter="all" value="全部">
        </div>
        <div class="layui-input-block aihao" >
            <input type="checkbox" name="like[write]" title="写作" lay-filter="aihao2" value="写作">
            <input type="checkbox" name="like[read]" title="阅读" lay-filter="aihao2" value="阅读">
        </div>
    </div>
</form>
layui.use(['form','element'], function(){
        var form = layui.form;
         //监听复选框-单个
        form.on('checkbox(aihao2)', function(data){
            if(data.elem.checked==true){
                $.each($('.aihao').children('div'),function(){
                    if($(this).hasClass('layui-form-checked')==false){
                        $('.all').children('div').removeClass('layui-form-checked');
                        $(".all input").prop("checked",false);
                        return false;
                    }else{
                        $('.all').children('div').addClass('layui-form-checked');
                        $(".all input").prop("checked",true);
                    }
                });
            }else{
                $('.all').children('div').removeClass('layui-form-checked');
                $(".all input").prop("checked",false);
            }
        });
        //监听复选框-全部
        form.on('checkbox(all)', function(data){
            if(data.elem.checked==true){
                $('.aihao').children('div').addClass('layui-form-checked');
                $(".aihao input").prop("checked",true);
            }else{
                $('.aihao').children('div').removeClass('layui-form-checked');
                $(".aihao input").prop("checked",false);
            }
 
        });
       
        //点击提交
        form.on('submit(*)',function(data){
            var formData =data.field;
            console.log( data.field);return false;
        });
    });

 

 类似资料: