前置条件使用select
1、引用相关文件
<link rel="stylesheet" href="../../../lib/layui/css/layui.css" media="all"/>
<script src="https://cdn.staticfile.org/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript" src="../../../lib/layui/select2.min.js"></script>
2、给select设置id
3、调用select2
$(document).ready(function() {
$("#xiaozheng").select2();
});
使用select2
$("#xiaozheng").select2();
数据初始化
1、静态数据初始化
标签的值的id,value的值为text
var data=[
{
"id": 0,
"text": "enhancement"
},
{
"id": 1,
"text": "bug"
},
{
"id": 2,
"text": "duplicate"
},
{
"id": 3,
"text": "invalid"
},
{
"id": 4,
"text": "wontfix"
}
];
$("#xiaozheng").select2({
data:[{id:0,text:'enhancement'},{id:1,text:'bug'},{id:2,text:'duplicate'},{id:3,text:'invalid'},{id:4,text:'wontfix'}]
});
2、远程初始化数据 ~ 利用ajax拿到id,text的数组对象,然后赋值操作
// 这个loadMerchant接口返回的数据格式就是{id: '', text: ''}数组对象
var merchantNameData = [{id: '', text: ''}];
$("#userNameUnit").select2({
ajax: {
url: "crossBorder_loadMerchant.action",
type: "post",
dataType: "json",
delay: 250,
async: false,
data: function (params) {
return {
criteria: params.term
};
},
processResults: function (data, page) {
merchantNameData = data;
return {
results: merchantNameData
};
},
cache: false
},
});
3、直接渲染数据
// Map<String, String> standardCurrencyMap = new LinkedHashMap<>();
// setAttribute("standardCurrencyInfo", standardCurrencyMap);
<select class="select radius size-M" style="width:140px;height: 31px;" size="1" id="form-feeCurrency" name="form-feeCurrency" required >
<option th:each="standardCurrency:${standardCurrencyInfo}" th:value="${standardCurrency.key}" th:text="${standardCurrency.value}" th:selected="${standardCurrency.key =='840'}"></option>
</select>
设置默认
1、渲染选中,默认选中key = 840的项
<option th:each="standardCurrency:${standardCurrencyInfo}" th:value="${standardCurrency.key}" th:text="${standardCurrency.value}" th:selected="${standardCurrency.key =='840'}"></option>
2、jq选中,在点击编辑时,回显默认值
$('#form-feeCurrency').val(d.feeCurrency).select2();
第二种方式:
$('#form-feeCurrency').val([d.feeCurrency]).trigger('change');
第二种方式会触发change事件
3、去除选中值
$('#mySelect2').val(null).trigger('change');
$('#mySelect2').val("").trigger('change');
设置多选
增加multiple="multiple"属性配置
<select id="curType" name = "curType" style="width: 380px;" class="js-states form-control" multiple="multiple">
<option value="" th:text="无"></option>
<option th:each="curType:${curTypeList}" th:value="${curType.numCode}"
th:text="${curType.getTemplate()}"></option>
</select>
获取数据
1、如果是单选:
// 跟JQ获取表格数据方式一样
var feeCurrency = $("#form-feeCurrency").val();
2、如果是多选的话,有两种方式获取数据
注意:如果用单选的方式获取数据,则得到的是NULL
2.1 增加改变事件,将变化的数据添加到隐藏域中,用“;”分割开
1、设置隐藏域
<input type="hidden" id="curTypeString" name="curTypeString">
2、改变事件触发
$('#curType').change(function(){
let o=document.getElementById('curType').getElementsByTagName('option');
let all="";
for(var i=0;i<o.length;i++){
if(o[i].selected){
all+=o[i].value+",";
}
}
all = all.substr(0, all.length - 1);//去掉末尾的逗号
console.log(all);
$("#curTypeString").val(all);//赋值给隐藏的文本框
});
2.2 然后将数据提交后后台,分割即系
第二种方式:直接获取,不需要监听事件
var arraySelected = $('#curType').select2("data");
var carTypesDesc = '';
for (var i = 0; i < arraySelected.length; i++) {
carTypesDesc += arraySelected[i].text;
carTypesDesc += "-";
carTypesDesc += arraySelected[i].id;
if (i != arraySelected.length - 1) {
carTypesDesc += ",";
}
}
id,text分别是option的key和value值
范程式变成
$("#e7").select2({
placeholder: "Search for a repository",
minimumInputLength: 3,
ajax: {
url: "https://api.github.com/search/repositories",
dataType: 'json',
quietMillis: 250,
data: function (term, page) { // page is the one-based page number tracked by Select2
return {
q: term, //search term
page: page // page number
};
},
results: function (data, page) {
var more = (page * 30) < data.total_count; // whether or not there are more results available
// notice we return the value of more so Select2 knows if more results can be loaded
return { results: data.items, more: more };
}
},
formatResult: repoFormatResult, // omitted for brevity, see the source of this page
formatSelection: repoFormatSelection, // omitted for brevity, see the source of this page
dropdownCssClass: "bigdrop", // apply css that makes the dropdown taller
escapeMarkup: function (m) { return m; } // we do not want to escape markup since we are displaying html in results
});
动态操作options
第一种方式:
$("#mySelect2'").html(''); // 这种方法证明是有效的!
第二种方式:
循环清除
之前做过的效果,如果a,则显示:1
如果b,则显示2
如果c,则显示3
自己封装的一些方法:添加单个,移除单个,移除全部(for循环然后移除单个),添加多个(for循环添加单个),选中
/**
* 判端某个字符串是否包含某个子串
* @param normalBuyCurrency
* @param data
*/
function contains(buyCurrency, data) {
return buyCurrency.indexOf(data) != -1;
}
/**
* 根据主键ID移除指定value的option
* @param selectId
* @param key
*/
function removeOptionToSelect(selectId, key){
$("#" + selectId + " option[value=\"" + key + "\"]").remove();
}
/**
* 在某主键增加可选择的下拉选项
*/
function appendOptionToSelect(selectId, key, value){
$("#" + selectId).append("<option value='" + key + "'>" + value + "</option>");
}
/**
* 移除所有的Option,插入相关的Option,并且显示选中部分
*/
function removeAndAddOptionAndSelected(selectId, shwoBuyCurrency, curTypeTo, isAll){
let allBuyCurType = JSON.parse(supportBuyCurTypeJson);
// 移除所有,显示部分
for(let key in allBuyCurType){
removeOptionToSelect(selectId, key);
}
// 显示部分
for(let key in allBuyCurType){
if(isAll != null){
if(contains(shwoBuyCurrency, key)){
appendOptionToSelect(selectId, key ,allBuyCurType[key]);
}
}else{
appendOptionToSelect(selectId, key ,allBuyCurType[key]);
}
}
$('#' + selectId).val([curTypeTo]).trigger('change');
}
后续又遇到新的功能会更新上来,希望对你们有帮助
个人建议,如果找不到你们需要的效果,去看看官网,花一个小时看看,会找你们想要的案例哦。
如果遇到select2下拉框不能输入的BUG,详细解决方法看这一篇
https://blog.csdn.net/xiaozhegaa/article/details/104796394