layui复选框checkbox全选和获取值的解决方案

layui复选框checkbox全选和获取值的解决方案_第1张图片

引入外部文件

    <script src="../js/jquery.min.js">script>
    <script src="layui/layui.js">script>
    <link rel="stylesheet" href="layui/css/layui.css">

HTML代码

<form class="layui-form">
    <div class="layui-form-item">
        <label class="layui-form-label">可见班级label>
        <input type="checkbox" name="" lay-skin="primary" id="class_all" lay-filter="class_all" title="全选">
        <div class="layui-input-block" id="check">
            <input type="checkbox" name="" lay-skin="primary" class="class_one" title="600110" value="600110">
            <input type="checkbox" name="" lay-skin="primary" class="class_one" title="600120" value="600120">
            <input type="checkbox" name="" lay-skin="primary" class="class_one" title="600130" value="600130">
            <input type="checkbox" name="" lay-skin="primary" class="class_one" title="600140" value="600140">
            <input type="checkbox" name="" lay-skin="primary" class="class_one" title="600150" value="600150">
        div>
    div>
form>
<button id="btn" class="layui-btn">提交button>

javascript代码

 layui.use(['form'], function () {
        let form = layui.form;
        //全选
        form.on('checkbox(class_all)', function (data) {
            var a = data.elem.checked;
            if (a == true) {
                $(".class_one").prop("checked", true);
                form.render('checkbox');
            } else {
                $(".class_one").prop("checked", false);
                form.render('checkbox');
            }
        });

        //有一个未选中全选取消选中;
        form.on('checkbox(class_one)', function (data) {
            var item = $(".class_one");
            for (var i = 0; i < item.length; i++) {
                if (item[i].checked == false) {
                    $("#class_all").prop("checked", false);
                    form.render('checkbox');
                }
            }
        });
    });

    $(function () {
        $("#btn").click(function () {
            var checkValue = [];
            $('#check input[type=checkbox]:checked').each(function () {
                checkValue.push($(this).val());
            });
            if (checkValue == "") {
                alert("请选择选项!");
                return false;
            } else {
                console.log(checkValue);
            }

        })
    })

Done !

你可能感兴趣的:(layui)