jQuery Select2 获取选择的选项数据
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26680587/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Select2 Get selected option data
提问by Kavvson
$("#e2").select2("val")
returns me the value, but I wan't to get the .$listtypes['name'] .
ether from data-name or from the option tag display.
$("#e2").select2("val")
返回值,但我不想.$listtypes['name'] .
从数据名称或选项标签显示中获取以太。
I want to get the option data-name for the selected option, how can I accomplish this?
我想获取所选选项的选项数据名称,我该如何完成?
This is my option generator
这是我的选项生成器
foreach($core->list_types() as $listtypes){
echo "
<option
data-name='".$listtypes['name'] ."'
value='".$listtypes['id']."'>
".$listtypes['name'] ."
</option>";
}
回答by xploshioOn
you can use this
你可以用这个
$("#e2 option:selected").text();
回答by Sasha Stadnik
Try this:
尝试这个:
$('#e2').select2('data')
$('#e2').select2('data')
return selected option data
返回选择的选项数据
回答by Luis Morales
This work for me:
这对我有用:
On simple select2to get label value:
在简单的select2上获取标签值:
$('#myVar').select2('data')[0].<name_label_from_data_input>
$('#myVar').select2('data')[0].<name_label_from_data_input>
May be helpful do an data dump from select2variable:
从select2变量中进行数据转储可能会有所帮助:
$('#myVar').on('change', function (evt) {
if ($('#myVar').select2('val') != null){
console.log($('#myVar').select2('data')[0]);
}
});
And catch your the label's name attribute.
并捕获您的标签名称属性。
Good luck!
祝你好运!
回答by yaser
You can use this script
你可以使用这个脚本
$('#editable-select').on('select2:select', function (e) {
var data = e.params.data;
console.log(data);
alert(data['text']);
});
回答by Hank
Looks that @Kishan and @xploshioOn's answers won't work on v4.0+.
看起来@Kishan 和@xploshioOn 的答案不适用于 v4.0+。
Try this: $("#e2").text().trim()
尝试这个: $("#e2").text().trim()
回答by Kishan
Use the attr method .attr("data-name")
on your selector.
.attr("data-name")
在选择器上使用 attr 方法。