formSelects-v4.js 基于Layui的多选解决方案

2020/05/21 19:09
阅读数 554
3、下载与使用
下载地址:   GitHub
使用文档: GitHub Pages
使用方式:

//1.下载formSelects-v4
 
//然后引入formSelects.css
<link rel="stylesheet" href="formSelects-v4.css" />
 
//2.模块化使用
<script src="layui.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
    //全局定义一次, 加载formSelects
    layui.config({
        base: '../src/' //此处路径请自行处理, 可以使用绝对路径
    }).extend({
        formSelects: 'formSelects-v4'
    });
    //加载模块
    layui.use(['jquery', 'formSelects'], function(){
        var formSelects = layui.formSelects;
         
    });
</script>
 
//3.非模块化使用
<script src="layui.all.js" type="text/javascript" charset="utf-8"></script>
<script src="formSelects-v4.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
    var formSelects = layui.formSelects;
     
</script>

 一个简单的小例子

HTML Result
EDIT ON
 <!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
        <title>formSelects-v4 多选</title>
    </head>
    <body>

        <link rel="stylesheet" type="text/css" href="https://raw.githack.com/hnzzmsf/layui-formSelects/master/dist/formSelects-v4.css" />
        
        <div>
            <select name="city" xm-select="select1">
                <option value="1" disabled="disabled">北京</option>
                <option value="2" selected="selected">上海</option>
                <option value="3">广州</option>
                <option value="4" selected="selected">深圳</option>
                <option value="5">天津</option>
            </select>
        </div>


        <script src="https://unpkg.com/jquery@3.4.1/dist/jquery.js" type="text/javascript" charset="utf-8"></script>
        <script src="https://raw.githack.com/hnzzmsf/layui-formSelects/master/dist/formSelects-v4.min.js" type="text/javascript"
         charset="utf-8"></script>
    </body>
</html>


Resources
4、基本参数
属性名 说明 示例
xm-select 多选核心, 标记不同的多选, 多选ID xm-select="id"
xm-select-max 多选最多选择数量 xm-select-max="3"
xm-select-skin 皮肤 xm-select-skin=" default | primary | normal | warm | danger "
xm-select-search 本地搜索 & 远程搜索 xm-select-search, xm-select-search="/search", 值为空时已有条目过滤搜索, 有值时开启远程搜索
xm-select-create 条目不存在时创建, 标记性属性 xm-select-create
xm-select-direction 下拉方向 xm-select-direction="auto|up|down", 自动, 上, 下, 默认自动模式
xm-select-radio 单选模式 xm-select-radio, 最多只能选择一个
xm-select-search-type 搜索框的显示位置 xm-select-search-type="title" 在下拉选title部分显示, xm-select-search-type="dl" 在选项的第二条显示
xm-select-show-count 多选显示的label数量 xm-select-show-count="2", 超出后隐藏
5、基本方法

value

/**
 * 1.获取选中数据
 *
 * formSelects.value(ID, TYPE);
 *
 * @param ID    xm-select的值
 * @param TYPE  all | val | valStr | name | nameStr
 */
var formSelects = layui.formSelects;
formSelects.value('select1');               // [{"name":"上海","val":"2"},{"name":"深圳","val":"4"}]
formSelects.value('select1', 'all');        // [{"name":"上海","val":"2"},{"name":"深圳","val":"4"}]
formSelects.value('select1', 'val');        // ["2","4"]
formSelects.value('select1', 'valStr');     // 2,4
formSelects.value('select1', 'name');       // ["上海","深圳"]
formSelects.value('select1', 'nameStr');    // 上海,深圳
 
 
/**
 * 2.设置select的选中值
 *
 * formSelects.value(ID, ARR);
 *
 * @param ID    xm-select的值
 * @param ARR   value数组
 */
var formSelects = layui.formSelects;
formSelects.value('select1', [2, 4]);       // 选中value为2和4的option → 上海,深圳
 
 
/**
 * 3.追加或删除select的选中值
 *
 * formSelects.value(ID, ARR, isAppend);
 *
 * @param ID    xm-select的值
 * @param ARR   value数组
 */
var formSelects = layui.formSelects;
formSelects.value('select1', [2, 4], true); // 追加value为2和4的option, 如果该值已选中则跳过, 该值未选中则选中
formSelects.value('select1', [2, 4], false);// 删除value为2和4的option, 如果该值没有选中则跳过, 该值被选中则取消选中

on


/**
 * 1.监听select的选中与取消
 *
 * formSelects.on(ID, Function);
 *
 * @param ID        xm-select的值
 * @param Function  自定义处理方法
 * @param isEnd     是否获取实时数据, true/false
 */
var formSelects = layui.formSelects;
formSelects.on('select1', function(id, vals, val, isAdd, isDisabled){
    //id:           点击select的id
    //vals:         当前select已选中的值
    //val:          当前select点击的值
    //isAdd:        当前操作选中or取消
    //isDisabled:   当前选项是否是disabled
     
    //如果return false, 那么将取消本次操作
    return false;   
});
 
//以下两种方式则配置所有的多选select
formSelects.on(function(id, vals, val, isAdd, isDisabled){
    ...
});
formSelects.on(null, function(id, vals, val, isAdd, isDisabled){
    ...
});
 
//4.0.0.0813版本之前, 受到了颇多的小伙伴吐槽, 此版本加上了获取实时数据的方法
formSelects.on('select1', function(id, vals, val, isAdd, isDisabled){
    //id:           点击select的id
    //vals:         当前select已选中的值
    //val:          当前select点击的值
    //isAdd:        当前操作选中or取消
    //isDisabled:   当前选项是否是disabled
     
}, true);

maxTips


/**
 * 1.多选select超出最大值的提示, 默认闪烁红色边框
 *
 * formSelects.maxTips(ID, Function);
 *
 * @param ID        xm-select的值
 * @param Function  自定义处理方法
 */
var formSelects = layui.formSelects;
formSelects.maxTips('select1', function(id, vals, val, max){
    //id:   点击select的id
    //vals: 当前select已选中的值
    //val:  当前select点击的值
    //max:  当天多选最大值
    alert("选超了...");
});
 
//以下两种方式则配置所有的多选select
formSelects.maxTips(function(id, vals, val, max){
    ...
});
formSelects.maxTips(null, function(id, vals, val, max){
    ...
});
filter

filter


/**
 * 1.自定义本地搜索过滤方式, 默认匹配文本是否包含
 *
 * formSelects.filter(ID, Function);
 *
 * @param ID        xm-select的值
 * @param Function  自定义处理方法
 */
var formSelects = layui.formSelects;
formSelects.filter('select1', function(id, inputVal, val, isDisabled){
    //id:           点击select的id
    //inputVal:     当前input搜索框中的数值
    //val:          格式: {"name":"上海","val":"2"}
    //isDisabled:   当前options是否被禁用
     
    //return true时该选项被过滤, 隐藏不显示
    return true;
});
 
//以下两种方式则配置所有的多选select
formSelects.filter(function(id, inputVal, val, isDisabled){
    ...
});
formSelects.filter(null, function(id, inputVal, val, isDisabled){
    ...
});

config

/**
 * 1.配置远程搜索, 请求头, 请求参数, 请求类型等
 *
 * formSelects.config(ID, Options, isJson);
 *
 * @param ID        xm-select的值
 * @param Options   配置项
 * @param isJson    是否传输json数据, true将添加请求头 Content-Type: application/json; charset=UTF-8
 */
var formSelects = layui.formSelects;
formSelects.config('select1', {
    type: 'get',                //请求方式: post, get, put, delete...
    header: {},                 //自定义请求头
    data: {},                   //自定义除搜索内容外的其他数据
    searchUrl: '',              //搜索地址, 默认使用xm-select-search的值, 此参数优先级高
    searchName: 'keyword',      //自定义搜索内容的key值
    searchVal: '',              //自定义搜索内容, 搜素一次后失效, 优先级高于搜索框中的值
    keyName: 'name',            //自定义返回数据中name的key, 默认 name
    keyVal: 'value',            //自定义返回数据中value的key, 默认 value
    keySel: 'selected',         //自定义返回数据中selected的key, 默认 selected
    keyDis: 'disabled',         //自定义返回数据中disabled的key, 默认 disabled
    keyChildren: 'children',    //联动多选自定义children
    delay: 500,                 //搜索延迟时间, 默认停止输入500ms后开始搜索
    direction: 'auto',          //多选下拉方向, auto|up|down
    response: {
        statusCode: 0,          //成功状态码
        statusName: 'code',     //code key
        msgName: 'msg',         //msg key
        dataName: 'data'        //data key
    },
    success: function(id, url, searchVal, result){      //使用远程方式的success回调
        console.log(id);        //组件ID xm-select
        console.log(url);       //URL
        console.log(searchVal); //搜索的value
        console.log(result);    //返回的结果
    },
    error: function(id, url, searchVal, err){           //使用远程方式的error回调
        //同上
        console.log(err);   //err对象
    },
    beforeSuccess: function(id, url, searchVal, result){        //success之前的回调, 干嘛呢? 处理数据的, 如果后台不想修改数据, 你也不想修改源码, 那就用这种方式处理下数据结构吧
        console.log(id);        //组件ID xm-select
        console.log(url);       //URL
        console.log(searchVal); //搜索的value
        console.log(result);    //返回的结果
         
        return result;  //必须return一个结果, 这个结果要符合对应的数据结构
    },
    beforeSearch: function(id, url, searchVal){         //搜索前调用此方法, return true将触发搜索, 否则不触发
        if(!searchVal){//如果搜索内容为空,就不触发搜索
            return false;
        }
        return true;
    },
    clearInput: false,          //当有搜索内容时, 点击选项是否清空搜索内容, 默认不清空
}, true);
 
//以下两种方式则配置所有的多选select
formSelects.config('select1', {
    ...
}, false);
formSelects.config(null, {
    ...
}, false);

render


/**
 * 1.重新渲染, 如果已经是多选则重置为初始值, 如果是初始select则渲染为多选 
 * 2.支持渲染时候改变多个参数
 *
 * formSelects.render(ID);
 *
 * @param ID        xm-select的值
 */
var formSelects = layui.formSelects;
formSelects.render('select1', {
    init: ["1", "2"],               //默认值
    skin: "danger",                 //多选皮肤
    height: "auto",                 //是否固定高度, 38px | auto
    radio: false,                   //是否设置为单选模式
    direction: "auto",
    create: function(id, name){
        console.log(id);    //多选id
        console.log(name);  //创建的标签名称
         
        return Date.now();  //返回该标签对应的val
    },          
    filter: fun...,         //同formSelects.filter           
    max: 3,                 //多选最多选择量           
    maxTips: fun...,        //同formSelects.maxTips
    on: fun...,             //同formSelects.on
    searchType: "title",    //搜索框的位置            
    template: function(name, value, selected, disabled){
        console.log(name);      //选项名
        console.log(value);     //选项值
        console.log(selected);  //是否被选中
        console.log(disabled);  //是否被禁用
         
        //例如: 反转字符串
        //return name.split('').reverse().join('');
        return name;        //返回一个html结构, 用于显示选项
    },
    showCount: 0,           //多选的label数量, 0,负值,非数字则显示全部
});
 
//以下方式则重新渲染所有的已存在多选
formSelects.render();

disabled


/**
 * 1.禁用多选
 *
 * formSelects.disabled(ID);
 *
 * @param ID        xm-select的值
 */
var formSelects = layui.formSelects;
formSelects.disabled('select1');
 
//以下方式则禁用所有的已存在多选
formSelects.disabled();

undisabled

/**
 * 1.启用多选, 启用被禁用的多选
 *
 * formSelects.undisabled(ID);
 *
 * @param ID        xm-select的值
 */
var formSelects = layui.formSelects;
formSelects.undisabled('select1');
 
//以下方式则启用所有的已存在多选
formSelects.undisabled();

data


/**
 * 1.多选数据赋值
 *
 * formSelects.data(ID, type, config);
 *
 * @param ID            xm-select的值
 * @param type          'local' | 'server', 本地数据或者远程数据
 * @param config        配置项
 *          arr             本地数据数组
 *          url             远程数据链接
 *          keyword         远程数据搜索内容, 其他附加数据可以使用 formSelects.config设置
 *          linkage         是否为联动多选
 *          linkageWidth    联动多选没级宽度
 */
 
//以下代码可以在console中运行测试, 结果查看基础示例第一个
var formSelects = layui.formSelects;
 
//local模式
formSelects.data('select1', 'local', {
    arr: [
        {"name": "分组-1", "type": "optgroup"},
        {"name": "北京", "value": 1},
        {"name": "上海", "value": 2},
        {"name": "分组-2", "type": "optgroup"},
        {"name": "广州", "value": 3},
        {"name": "深圳", "value": 4},
        {"name": "天津", "value": 5}
    ]
});
 
//server模式
formSelects.data('select1', 'server', {
    url: 'https://www.fastmock.site/mock/29487363107ab7d242c46305cadf4c52/formSelects/layui/data',
    keyword: '水果'
});
//server返回数据与远程搜索数据结构一致
{
    "code":0,
    "msg":"success",
    "data":[
        {"name":"北京","value":1,"selected":"","disabled":""},
        {"name":"上海","value":2,"selected":"","disabled":""},
        {"name":"广州","value":3,"selected":"selected","disabled":""},
        {"name":"深圳","value":4,"selected":"","disabled":"disabled"},
        {"name":"天津","value":5,"selected":"","disabled":""}
    ]
}
//当然你也可以偷懒, 返回如下结构
[
    {"name":"北京","value":1,"selected":"","disabled":""},
    {"name":"上海","value":2,"selected":"","disabled":""},
    {"name":"广州","value":3,"selected":"selected","disabled":""},
    {"name":"深圳","value":4,"selected":"","disabled":"disabled"},
    {"name":"天津","value":5,"selected":"","disabled":""}
]
 
/*************** 华丽的分割线 ***************/
//来一个树状结构的数据
formSelects.data('select15', 'local', {
    arr: [
        {name: '北京', value: 1, xslkdf: '123', children: [
            {name: '朝阳', value: 11}, 
            {name: '海淀', value: 12}
        ]},
        {name: '深圳', value: 2, children: [{name: '龙岗', value: 21}]},
    ]
});
 
 
/*************** 华丽的分割线 ***************/
//联动多选数据格式
//local, 注意 value值请保证唯一
formSelects.data('select15', 'local', {
    arr: [
        {
            "name": "北京", 
            "value": 1, 
            "children": [
                {"name": "北京市1", "value": 12, "children": [
                    {"name": "朝阳区1", "value": 13, "children": []},
                    {"name": "朝阳区2", "value": 14, "children": []},
                    {"name": "朝阳区3", "value": 15, "children": []},
                    {"name": "朝阳区4", "value": 16, "children": []},
                ]},
                {"name": "北京市2", "value": 17, "children": []},
                {"name": "北京市3", "value": 18, "children": []},
                {"name": "北京市4", "value": 19, "children": []},
            ]
        },
        {
            "name": "天津", 
            "value": 2, 
            "children": [
                {"name": "天津市1", "value": 51, "children": []},
            ]
        },
    ],
    linkage: true   //开启联动模式
});
 
//server
formSelects.data('select15', 'server', {
    url: 'http://yapi.demo.qunar.com/mock/9813/layui/citys',
    linkage: true,
    linkageWidth: 130   //代表每一级别的宽度, 默认是100
});
//server返回数据, 同上 value不能重复
{
    "code":0,
    "msg":"success",
    "data":[
        {
            "name": "北京", 
            "value": 1, 
            "children": [
                {"name": "北京市1", "value": 12, "children": [
                    {"name": "朝阳区1", "value": 13, "children": []},
                    {"name": "朝阳区2", "value": 14, "children": []},
                    {"name": "朝阳区3", "value": 15, "children": []},
                    {"name": "朝阳区4", "value": 16, "children": []},
                ]},
                {"name": "北京市2", "value": 17, "children": []},
                {"name": "北京市3", "value": 18, "children": []},
                {"name": "北京市4", "value": 19, "children": []},
            ]
        },
        {
            "name": "天津", 
            "value": 2, 
            "children": [
                {"name": "天津市1", "value": 51, "children": []},
            ]
        },
    ]
}

btns


/**
 * 1.快捷操作
 *
 * formSelects.btns(ID, BTNS, config);
 *
 * @param ID        xm-select的值
 * @param BTNS      定义操作列表, 内置三种操作, select:全选, remove:清空, skin:换肤, 当然你可以自定义
 * @param config    配置操作列表, config.show='name' 只显示名称, config.show='icon' 只显示图标, config.space='30px' 两个操作之间的间隔
 */
var formSelects = layui.formSelects;
//默认设置了 全选, 清空, 反选
//如下设置内置操作
formSelects.btns('select1', ['select', 'remove', 'reverse']);
 
//如下设置自定义
formSelects.btns('select1', ['select', 'remove', 'skin', {
    icon: 'layui-icon layui-icon-ok',   //自定义图标, 可以使用layui内置图标
    name: '提示名称',
    click: function(id){
        //点击后的操作
        alert('点击了自定义快捷操作')
    }
}]);
 
//配置只显示名称,紧凑型, 适合宽度较窄的情况
formSelects.btns('select1', ['select', 'remove'], {show: 'name', space: '10px'});
 
//如下写法定义所有的多选
formSelects.btns(['select', 'remove', 'skin']);
 
// !!友情提示: name不能重复

search


/**
 * 1.触发搜索
 *
 * formSelects.search(ID, val);
 *
 * @param ID        xm-select的值
 * @param BTNS      搜索内容
 */
var formSelects = layui.formSelects;
 
//使用js主动触发搜索
formSelects.search('select1', '关键内容');

opened


/**
 * 1.打开下拉框的回调事件
 *
 * formSelects.opened(ID);
 *
 * @param ID        xm-select的值
 */
var formSelects = layui.formSelects;
 
//监听下拉框的打开
formSelects.opened('select1', function(id){
    console.log('打开了');
});
 
//如下定义所有
formSelects.opened(null, function(id){
    console.log('打开了');
});
formSelects.opened(function(id){
    console.log('打开了');
});

closed

/**
 * 1.关闭下拉框的回调事件
 *
 * formSelects.closed(ID);
 *
 * @param ID        xm-select的值
 */
var formSelects = layui.formSelects;
 
//监听下拉框的关闭
formSelects.closed('select1', function(id){
    console.log('合上了');
});
 
//如下定义所有
formSelects.closed(null, function(id){
    console.log('合上了');
});
formSelects.closed(function(id){
    console.log('合上了');
});
6、基础示例

基础多选

适用性较广的基础多选,用 Tag 展示已选项

 
<select name="city" xm-select="select1">
    <option value="1" disabled="disabled">北京</option>
    <option value="2" selected="selected">上海</option>
    <option value="3">广州</option>
    <option value="4" selected="selected">深圳</option>
    <option value="5">天津</option>
</select>

pane模式

layui pane模式

<div class= "layui-form layui-form-pane" >
     <div class= "layui-form-item" >
         <label class= "layui-form-label" >多选框</label>
         <div class= "layui-input-block" >
             <select name= "city" xm-select= "select2" >
                 <option value= "1" disabled= "disabled" >北京</option>
                 <option value= "2" selected= "selected" disabled= "disabled" >上海</option>
                 <option value= "3" >广州</option>
                 <option value= "4" selected= "selected" >深圳</option>
                 <option value= "5" >天津</option>
             </select>
         </div>
     </div>
</div>

 

分组多选

基于layui的分组多选

<select name= "city" xm-select= "select3" >
     <optgroup label= "分组1" >
         <option value= "1" disabled= "disabled" >北京</option>
         <option value= "2" selected= "selected" >上海</option>
     </optgroup>
     <optgroup label= "分组2" >
         <option value= "3" >广州</option>
         <option value= "4" selected= "selected" >深圳</option>
         <option value= "5" >天津</option>
     </optgroup>
</select>

多选上限

xm-select-max="3", 超过3个后, 默认闪烁红框提示

 

<select name= "city" xm-select= "select5" xm-select-max= "3" >
     <option value= "" >啦啦, 我是自定义的</option>
     <option value= "1" disabled= "disabled" >北京</option>
     <option value= "2" selected= "selected" >上海</option>
     <option value= "3" >广州</option>
     <option value= "4" selected= "selected" >深圳</option>
     <option value= "5" >天津</option>
</select>

本地搜索

xm-select-search, 搜索已存在的option

 

<select name= "city" xm-select= "select7_1" xm-select-search= "" >
     <option value= "1" disabled= "disabled" >北京</option>
     <option value= "2" selected= "selected" >上海</option>
     <option value= "3" >广州</option>
     <option value= "4" selected= "selected" >深圳</option>
     <option value= "5" >天津</option>
</select>

 

远程搜索

xm-select-search="/search", 指定一个url, 将开启远程搜索模式

<select name= "city" xm-select= "select8" xm-select-search= "https://www.fastmock.site/mock/29487363107ab7d242c46305cadf4c52/formSelects/layui/data" >
     <option value= "1" disabled= "disabled" >北京</option>
     <option value= "2" selected= "selected" >上海</option>
     <option value= "3" >广州</option>
     <option value= "4" selected= "selected" >深圳</option>
     <option value= "5" >天津</option>
</select>

远程搜索response结构, 其中name, value可以自定义, 请查看method config

code为0时, 表示正常, 不为0时则提示msg信息

 
{
     "code" : 0,
     "msg" : "success" ,
     "data" : [
         { "name" : "北京" , "value" :1, "selected" : "" , "disabled" : "" },
         { "name" : "上海" , "value" :2, "selected" : "" , "disabled" : "" },
         { "name" : "广州" , "value" :3, "selected" : "selected" , "disabled" : "" },
         { "name" : "深圳" , "value" :4, "selected" : "" , "disabled" : "disabled" },
         { "name" : "天津" , "value" :5, "selected" : "" , "disabled" : "" }
     ]
}

应用实例:


<link  href="public/assets/js/layui/formSelects-v4.css" rel="stylesheet" type="text/css" />
<script src="public/assets/js/layui/layui.js"></script>
<script src="public/assets/js/layui/formSelects-v4.min.js"></script>

<select name="eBayUser1$ddleBayUser" id="eBayUser1_ddleBayUser" lay-verify="required" lay-filter="eBayUser1_ddleBayUser" xm-select="eBayUser1_ddleBayUser" xm-select-search="" xm-select-type="10" style="position: absolute;bottom: 0;">
    <option value="14">14</option>
    <option value="16">16</option>
    <option value="18">18</option>
    <option value="20">20</option>
    <option value="22">22</option>
</select>

<script>
$(function(){
       //加载模块
        layui.use(['form'], function () {
            var form = layui.form;
            var formSelects = layui.formSelects;
            form.render();
            formSelects.btns('eBayUser1_ddleBayUser', ['select', 'remove', 'reverse'], {space: '10px'});

        });

        var formSelects = layui.formSelects;
        //获取选中值
        var ids = formSelects.value('eBayUser1_ddleBayUser', 'valStr');
       //点击完获取数据
        formSelects.on('eBayUser1_ddleBayUser', function(id, vals, val, isAdd, isDisabled){
            var ids = formSelects.value('eBayUser1_ddleBayUser', 'valStr');
           if(ids != ''){
                alert(ids);
            }else{
                 alert(111);
            }
        }, true);

 

展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部