表单数据这一块 layui 做的是真的不好,无论是在渲染还是在交互方面,每次都要自己来重新实现代码

#贴上代码

<!DOCTYPE html>
<head>
    <meta charset="utf-8">
    <title>Layui 监听 复选框 提价表单</title>
    <link rel="stylesheet" type="text/css" href="//layui.hcwl520.com.cn/layui/css/layui.css?v=201801090202"/>
</head>
<body>
<form class="layui-form p-3" autocomplete="off" οnsubmit="return false">
    <div class="layui-form-item">
        <label class="layui-form-label">复选框</label>
        <div class="layui-input-inline">
            <input type="text" name="number" value="0,1,3,4,5,6," disabled>
            <input type="checkbox" lay-filter="number" lay-skin="primary" value="0" title="0">
            <input type="checkbox" lay-filter="number" lay-skin="primary" value="1" title="1">
            <input type="checkbox" lay-filter="number" lay-skin="primary" value="2" title="2">
            <input type="checkbox" lay-filter="number" lay-skin="primary" value="3" title="3">
            <input type="checkbox" lay-filter="number" lay-skin="primary" value="4" title="4">
            <input type="checkbox" lay-filter="number" lay-skin="primary" value="5" title="5">
            <input type="checkbox" lay-filter="number" lay-skin="primary" value="6" title="6">
            <input type="checkbox" lay-filter="number" lay-skin="primary" value="7" title="7">
            <input type="checkbox" lay-filter="number" lay-skin="primary" value="8" title="8">
        </div>
    </div>
</form>
<script src="//layui.hcwl520.com.cn/layui/layui.js?v=201801090202"></script>
<script>

    layui.use(['form', 'laydate'], function () {
        var $ = layui.$//Jquery
            , form = layui.form;//表单
        //页面加载的时候就初始几个值
        initValue();

        //监听复选框
        form.on('checkbox(number)', function (data) {
            var number = $('input[name="number"]'), value = data.value, array = number.val().split(",");
            if (data.elem.checked) {
                number.val(number.val() + value + ",");
            } else {
                var newnumber = "";
                for (var i = 0; i < array.length; i++) {
                    var str = array[i];
                    newnumber += (str != value && str != "" && str != null) ? str + "," : "";
                }
                number.val(newnumber);
            }
        });

        /**
         * input 框初始 赋值 到checkedbox上
         * @author lengff
         */
        function initValue() {
            var param=$("input[name='number']").val(),checkBoxs = $("input[type='checkbox']"), array = param.split(",");
            for (var i = 0; i < array.length; i++) {
                for (var j = 0; j < checkBoxs.length; j++) {
                    var checkbox = $(checkBoxs[j]);
                    if (checkbox.val() == array[i]) {
                        checkbox.attr('checked','checked');
                        break;
                    }
                }
            }
            form.render('checkbox');
        }
    });
</script>
</body>
</html>
02-13 23:21