不廢話,上圖!
上代碼!
<!DOCTYPE html>
<html>
<head>
<title>表格數據源</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- 引入 Bootstrap -->
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/select2.min.css" rel="stylesheet" />
<!-- 加載 Jquery -->
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<!-- 包括所有已編譯的插件 -->
<script src="js/bootstrap.min.js"></script>
<!-- 加載 Select2 -->
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/select2.min.js"></script>
</head>
<body>
<h4>原始數據集</h4>
<p id="sourceData"></p>
<h4>數據源</h4>
<table id="theTable" style="border: 1px solid black">
<thead>
<td>序號</td>
<td>設備型號</td>
<td>採集數據</td>
</thead>
<tbody>
<tr>
<td>1</td>
<td>華爲M20,華爲M30</td>
<td><button οnclick="OnClickBtn(this)">顯示到select2</button></td>
</tr>
<tr>
<td>2</td>
<td>華爲P30,華爲P40</td>
<td><button οnclick="OnClickBtn(this)">顯示到select2</button></td>
</tr>
</tbody>
</table>
<h4>多選select2——默認選中多個</h4>
<select id="mobileModel" class="form-control js-example-basic-multiple" style="width: 200px">
</select>
<script>
var sourceData = [
{
id:0,
text:"華爲M20",
},{
id:1,
text:"華爲M30",
},{
id:2,
text:"華爲P30",
},{
id:3,
text:"華爲P40",
},{
id:4,
text:"華爲P50",
},{
id:5,
text:"華爲P60",
}
]
$(document).ready(function(){
document.getElementById("sourceData").innerHTML = JSON.stringify(sourceData);
InitSelect2();
})
//初始化select2
function InitSelect2(){
$("#mobileModel").select2({
data:sourceData,
placeholder: "請選擇",
allowClear: true,
multiple: true,
closeOnSelect: false,
escapeMarkuo: function(markup){
return markup;
},
minimumInputLength: 0,
templateResult: function formatRepo(repo){
var state = $('<span>' + repo.text + '</span>')
return state;
},
templateSelection: function formatRepoSelection(repo){
var state = $('<span style="background-color:lightskyblue">' + repo.text + '</span>')
return state;
},
})
}
function OnClickBtn(obj){
var rowindex = $(obj).parent().parent().index(); //行號
var oTable = document.getElementById("theTable");
var tDataStr = oTable.rows[rowindex + 1].cells[1].innerHTML;//取到表格中的數據
var tDataArr = tDataStr.split(",");
var arr = [];
for(const sourText in sourceData){
for(const tData in tDataArr){
//假定當前只有表格中的字符串可用,與數據源比對,相同則取出id保存
if(tDataArr[tData] === sourceData[sourText].text){
arr.push(sourceData[sourText].id);
}
}
}
//循環結束,得到對應的id數組
$("#mobileModel").val(arr).trigger('change');
}
</script>
</body>
</html>