前置條件使用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