'How to add a data-* attribute to each option when creating a select2 input?
I am using select2 to select from a list the image that I want to be displayed on the screen. For this I need to set an attribute on each option: s3_key
I want to put this attribute when the select2 is created
I have seen solutions to add data-* attributes when an option is selected. This solution doesn't work for me because if the input already has a value selected when loading the web page, the image has to be displayed automatically.
$('#id-gci-main').select2({
language: '<?= getLanguage() ?>',
closeOnSelect: true,
allowClear: true,
placeholder: '',
data: <?= $aJsonGCIsPrincipalesOtorgados ?>
}).on('select2:select', function (e) {
var data = e.params.data;
$(this).children('[value="'+data['id']+'"]').attr({
'data-s3_key':data["s3_key"], //dynamic value from data array
});
}).val(0).trigger('load');
The variable $aJsonGCIsPrincipalesOtorgados has the following structure:
var data = [
{
id: 1,
text: 'xxxx'.
s3_key: '/xx/image.png'
},
Is there any way to do this?
Example code:
Solution 1:[1]
don't do that, simply use a js Object select2data:
const data1 =
[ { id: 'key_1', text: 'YY', s3_key: 'xxxx/yy.png' }
, { id: 'key_2', text: 'BB', s3_key: 'wwww/bb.png' }
, { id: 'key_3', text: 'AAA', s3_key: 'wwww/aaa.png' }
]
const select2data = data1.reduce((r,{id,...more})=>(r[id]=more,r),{})
// console.log( select2data )
$("#id-gci-main").select2(
{ closeOnSelect : true
, allowClear : true
, placeholder : ''
, data : data1
}
).on('change', function(e)
{
console.clear()
console.log( select2data[this.value].s3_key )
});
#id-gci-main {
width : 300px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/select2.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/select2.min.js"></script>
<select id="id-gci-main" ></select>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
