Layui 表单 多选模拟单选,checkbox实现radio效果

Deadly 提交于 2019-12-24 06:08:24
<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <title>Layui 表单 多选模拟单选,checkbox实现radio效果</title>
    <link rel="stylesheet" href="../assets/libs/layui/css/layui.css" media="all">
</head>
<body>
<div class="layui-form">
    <br>
    <div class="layui-form-item">
        <label class="layui-form-label">选一个你的兴趣爱好</label>
        <div class="layui-input-block" isradio="true">
            <input type="checkbox" lay-skin="primary" lay-filter="cb_r" title="唱">
            <input type="checkbox" lay-skin="primary" lay-filter="cb_r" title="跳">
            <input type="checkbox" lay-skin="primary" lay-filter="cb_r" title="Rap">
            <input type="checkbox" lay-skin="primary" lay-filter="cb_r" title="打篮球">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">选多个你的兴趣爱好</label>
        <div class="layui-input-block" isradio="false">
            <input type="checkbox" lay-skin="primary" lay-filter="cb_r" title="唱">
            <input type="checkbox" lay-skin="primary" lay-filter="cb_r" title="跳">
            <input type="checkbox" lay-skin="primary" lay-filter="cb_r" title="Rap">
            <input type="checkbox" lay-skin="primary" lay-filter="cb_r" title="打篮球">
        </div>
    </div>
</div>
<script src="../assets/libs/layui/layui.js"></script>
<script>
    layui.use(['form', 'layer', 'jquery'], function () {
        var form = layui.form;
        var $ = layui.$;

        form.render();

        // 监听复选框操作,模拟单选
        form.on('checkbox(cb_r)', function (data) {
            let elem = data.elem;
            let parentDom = $(elem).parent();
            let isradio = $(parentDom).attr('isradio');
            let index = $(elem).index('input[type=checkbox]');
            if ('true' == isradio) {
                // 单选
                $(parentDom).children('input[type=checkbox]').prop('checked', false);
                $(elem).prop('checked', true);
                form.render('checkbox');
            } else {
                // 多选什么也不做
            }
        });
    });
</script>
</body>
</html>

效果图:
checkbox实现radio效果图

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!