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