最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Add custom attribute to option in select2 - Stack Overflow

programmeradmin0浏览0评论

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 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

Share Improve this question asked Apr 4, 2017 at 7:57 JayJay 8413 gold badges19 silver badges51 bronze badges
Add a comment  | 

3 Answers 3

Reset to default 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 : when select "Option 2" :

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

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");
发布评论

评论列表(0)

  1. 暂无评论