Add custom attribute to option in select2
Asked Answered
A

3

7

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

Autotype answered 4/4, 2017 at 7:57 Comment(0)
S
11

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

Selfdrive answered 15/1, 2018 at 3:26 Comment(0)
B
1

select2 use like this way :

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

Brood answered 4/4, 2017 at 9:33 Comment(0)
P
0

easiest way to manually add custom attribute to a select2 option is:

 for(var i = 0; i < arr.length; i++)
    {
        $('#id').append('<option attributename="'+arr[i].attributevalue+'" value="'+arr[i].Id+'">'+arr[i].Text+'</option>');
    }
    

after appending the html options we need to call select2() function

    $('#id').select2();

and then if you want to retrieve the data then you have to get it from the element like this:

$($('#id').select2('data')[0].element).attr("attributename");
Padua answered 10/5, 2023 at 9:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.