select2 - 获取点击框的值
select2 - Get the value of the clicked box
在我的 Select2 多 select 框中,我希望能够单击 selected 框并获取它们相应的选项值(或对象)。
这是(简而言之)到目前为止我所拥有的:
$('#mySelect2').next('span').find('ul').on('click', '.select2-selection__choice', function (e) {
console.log($('#mySelect2').select2('data'));
alert($(this).data('select2-id'));
});
我搜索了 select2 数据对象,但没有与点击框和 select2-id 数据属性相关的任何内容
似乎是随机的。
我在哪里可以找到一些匹配的 ID?
可以尝试下面的代码,使用 select2 - select 和 unselect 事件。
$("#mySelect2").on("select2:select select2:unselect", function (e) {
//get all items by, for multiple an array like ["9", "20"] will be returned
var items= $(this).val();
//Last selected value
var lastItem = e.params.data.id;
})
我想我找到了解决方法。
好像select2在rending列表中使用了title属性
所以诀窍是在每个选项中使用此属性作为 id。
<select multiple id="states" name="states[]" class="select2">
<option title="states-AL" value="AL">Alabama</option>
<option title="states-CA" value="CA">California</option>
<option title="states-MI" value="MI">Michigan</option>
<option title="states-UT" value="UT">Utah</option>
<option title="states-WY" value="WY">Wyoming</option>
</select>
$('#states').next('span').find('ul').on('click', '.select2-selection__choice', function (e) {
alert($(this).attr('title'));
});
在我的 Select2 多 select 框中,我希望能够单击 selected 框并获取它们相应的选项值(或对象)。
这是(简而言之)到目前为止我所拥有的:
$('#mySelect2').next('span').find('ul').on('click', '.select2-selection__choice', function (e) {
console.log($('#mySelect2').select2('data'));
alert($(this).data('select2-id'));
});
我搜索了 select2 数据对象,但没有与点击框和 select2-id 数据属性相关的任何内容
似乎是随机的。
我在哪里可以找到一些匹配的 ID?
可以尝试下面的代码,使用 select2 - select 和 unselect 事件。
$("#mySelect2").on("select2:select select2:unselect", function (e) {
//get all items by, for multiple an array like ["9", "20"] will be returned
var items= $(this).val();
//Last selected value
var lastItem = e.params.data.id;
})
我想我找到了解决方法。
好像select2在rending列表中使用了title属性
所以诀窍是在每个选项中使用此属性作为 id。
<select multiple id="states" name="states[]" class="select2">
<option title="states-AL" value="AL">Alabama</option>
<option title="states-CA" value="CA">California</option>
<option title="states-MI" value="MI">Michigan</option>
<option title="states-UT" value="UT">Utah</option>
<option title="states-WY" value="WY">Wyoming</option>
</select>
$('#states').next('span').find('ul').on('click', '.select2-selection__choice', function (e) {
alert($(this).attr('title'));
});