Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add custom attribute to option in select2

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

like image 744
Jay Avatar asked Apr 04 '17 07:04

Jay


1 Answers

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 : enter image description here when select "Option 2" : enter image description here

like image 115
tinyhare Avatar answered Nov 07 '22 16:11

tinyhare