Select2 - 下拉对象 ID
Select2 - dropdown object id
我可以获取 select2
下拉列表中所选值的 objectid
吗?
$('#buildParcelID option:selected').val();
是我获取值的方式,但我不确定如何获取 ID。这是我的对象的样子
根据文档here,可以使用 select2 数据方法检索所选选项的对象。
$('#mySelect').select2('data');
这将 return 一个数组,因为如果 multiple
选项设置为 true,则可以选择多个选项。数组中的对象将作为数据传递(或通过 ajax 加载),包括任何额外的属性。
下面的示例以及 https://jsfiddle.net/6Lnpusra/ 中的示例有几个额外的属性,这些属性会在选择时打印到控制台。
// Define some data with additional properties
let data = [
{
id: 1,
text: 'Test 1',
extraProperty: 'Extra 1',
objectId: 1001
},
{
id: 2,
text: 'Test 2',
extraProperty: 'Extra 2',
objectId: 1002
},
{
id: 3,
text: 'Test 3',
extraProperty: 'Extra 3',
objectId: 1003
}
];
// Initialise select2
$('#mySelect').select2({
placeholder: 'Select value...',
data: data
});
// Setup selection event
$('#mySelect').on('select2:select', function (e) {
// Fetch the selections array
let selections = $('#mySelect').select2('data');
// If one selection has been made print it's additional properties
if(selections.length > 0){
console.log(`Extra Property: '${selections[0].extraProperty}' - Object ID: ${selections[0].objectId}`);
}
});
#mySelect {
width: 300px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
<select id="mySelect"><option></option></select>
我可以获取 select2
下拉列表中所选值的 objectid
吗?
$('#buildParcelID option:selected').val();
是我获取值的方式,但我不确定如何获取 ID。这是我的对象的样子
根据文档here,可以使用 select2 数据方法检索所选选项的对象。
$('#mySelect').select2('data');
这将 return 一个数组,因为如果 multiple
选项设置为 true,则可以选择多个选项。数组中的对象将作为数据传递(或通过 ajax 加载),包括任何额外的属性。
下面的示例以及 https://jsfiddle.net/6Lnpusra/ 中的示例有几个额外的属性,这些属性会在选择时打印到控制台。
// Define some data with additional properties
let data = [
{
id: 1,
text: 'Test 1',
extraProperty: 'Extra 1',
objectId: 1001
},
{
id: 2,
text: 'Test 2',
extraProperty: 'Extra 2',
objectId: 1002
},
{
id: 3,
text: 'Test 3',
extraProperty: 'Extra 3',
objectId: 1003
}
];
// Initialise select2
$('#mySelect').select2({
placeholder: 'Select value...',
data: data
});
// Setup selection event
$('#mySelect').on('select2:select', function (e) {
// Fetch the selections array
let selections = $('#mySelect').select2('data');
// If one selection has been made print it's additional properties
if(selections.length > 0){
console.log(`Extra Property: '${selections[0].extraProperty}' - Object ID: ${selections[0].objectId}`);
}
});
#mySelect {
width: 300px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
<select id="mySelect"><option></option></select>