[英]Add custom attribute to option in select2
I am using select2 plugin, in that I want to add custom attribute to options "data-value". 我正在使用select2插件,因为我想将自定义属性添加到选项“data-value”。
$('select').select2({
data: [
{
id: 'value',
text: 'Text to display'
},
]
});
If I add "data-value" in above code it will not display that option. 如果我在上面的代码中添加“数据值”,它将不会显示该选项。 Is there any way to do such thing.
有没有办法做这样的事情。 I am using 4.* select2 plugin
我正在使用4. * select2插件
I use Select2 4.0.5 with the help of Event 'select2:select' to achieve this. 我在事件'select2:select'的帮助下使用Select2 4.0.5来实现这一点。
At initialization there is no effect, when you select one option, the attribute will add to it. 在初始化时没有任何效果,当您选择一个选项时,该属性将添加到该选项。
$(element).select2(
{
placeholder:'chose one option',
data:[ {
"id": 1,
"text": "Option 1",
"data-value":"dv1",
},
{
"id": 2,
"text": "Option 2",
"data-value":"dv2",
}]
}).on('select2:select', function (e) {
var data = e.params.data;
$(this).children('[value="'+data['id']+'"]').attr(
{
'data-value':data["data-value"], //dynamic value from data array
'key':'val', // fixed value
}
);
}).val(0).trigger('change');
the .val(0).trigger('change')
used for show placeholder and let it no default. 用于显示占位符的
.val(0).trigger('change')
并且没有默认值。 otherwise the first option will be default with no attribute add on. 否则第一个选项将是默认值,没有添加属性。
select2 use like this way : select2使用这种方式:
for(var i = 0; i < arr.length; i++)
{
$('select').append('<option data-value="'+arr[i].DataValue+'" value="'+arr[i].Id+'">'+arr[i].Text+'</option>');
}
$('select').select2();
after appending the options you need to call select2()
function 在附加选项后,您需要调用
select2()
函数
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.