用layui实现下拉框select多选,取值
首先需要的js及css,可以直接在layui官网上下载:https://www.layui.com/
相关引用:
<script src="~/layui-v2.4.5/layui/layui.js"></script>
<script src="~/layui-v2.4.5/layui/layui.all.js"></script>
<link href="~/layui-v2.4.5/layui/css/layui.css" rel="stylesheet" />
<script src="~/layui-v2.4.5/layui/lay/modules/layer.js"></script>
增加如下测试html代码:
<div class="layui-form">
<div class="layui-fluid">
<div class="layui-form layui-col-md12">
<div class="layui-form-item">
<div class="layui-col-md4">
<label class="layui-form-label">城市<span style="color:red">●</span></label>
<div class="layui-input-block">
<select name="select_base_cityname" id="select_base_cityname" lay-filter="select_base_cityname" xm-select="select_base_cityname" xm-select-type="1">
<option value=""></option>
<option value="1">北京</option>
<option value="2">上海</option>
<option value="3">天津</option>
<option value="4">重庆</option>
</select>
</div>
</div>
</div>
<div class="layui-row ">
<div class="test-table-reload-btn" style="margin-bottom: 10px;">
<button type="button" class="layui-btn layui-btn-danger" lay-submit lay-filter="btn_submit" id="btn_submit"><i class="layui-icon"></i>获取</button>
</div>
</div>
</div>
</div>
</div>
配置select多选相关:
<link href="~/layui-v2.4.5/layui/formSelects-v4.css" rel="stylesheet" />
<script src="~/layui-v2.4.5/layui/formSelects-v4.js"></script>
<script type="text/javascript">
//全局定义一次, 加载formSelects
layui.config({
base: '/' //此处路径请自行处理, 可以使用绝对路径
}).extend({
formSelects: 'formSelects-v4'
});
//加载模块
layui.use(['jquery', 'formSelects'], function () {
//初始化select多选
var formSelects = layui.formSelects;
});
</script>
到这一步,已经能显示多选效果了,如图:
接下来就直接获取选择的值就行了:
<script type="text/javascript">
layui.use(['form', 'layer', 'jquery', 'table', 'laydate', 'element', 'upload', 'flow'], function () {
var $$ = layui.jquery;
var form = layui.form,
layer = parent.layer == undefined ? layui.layer : parent.layer,
//layer = layui.layer,
table = layui.table,
laydate = layui.laydate,
element = layui.element,
upload = layui.upload,
flow = layui.flow;
form.render();
form.on('submit(btn_submit)', function (obj) {
layer.confirm('确认录入无误吗?', {
btn: ['确认', '再看看']
}, function () {
var getName = JSON.stringify(layui.formSelects.value('select_base_cityname', 'name'));//取值name数组
layer.msg("你选择的值为:" + getName, { offset: '150px', icon: 1, time: 5000 }, function () {
});
//获取select多选框的value值
var getValue = JSON.stringify(layui.formSelects.value('select_base_cityname', 'valStr'));//取值select多选框的value值
layer.msg("你选择的select value值为:" + getValue , { offset: '150px', icon: 1, time: 5000 }, function () {
});
//默认选中
formSelects.value('select_base_cityname', ['1','2']);//赋值选中,为option的value值,数组形式,给北京和上海选中
});
});
});
</script>
更详细的文档,可以参考:https://fly.layui.com/extend/formSelects/#doc
总结:layui还是相对不错的前端框架,在一些项目中,都会看到它的身影。