I am using select2 plugin, in that I want to add custom attribute to options "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
I use Select2 4.0.5 with the help of Event 'select2:select' to achieve this.
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. otherwise the first option will be default with no attribute add on.
Init : when select "Option 2" :
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With