Jquery select2 json data with optgroup and images
Select2 maps data objects to <option>
and <optgroup>
tags using the following logic
A data object (what is returned in the list) that looks like
{
'id': 'value-here',
'text': 'text-here'
}
Will be mapped to an <option>
that looks like
<option value="value-here">text-here</option>
A data object that looks like
{
'text': 'label-here',
'children': [data_object, data_object]
}
Will be mapped into an <optgroup>
that looks like
<optgroup label="label-here">
<!-- HTML for the `children` -->
</optgroup>
So the data object that you are looking to return is
{
'text': 'group',
'children': [
{
'id': 'imageName',
'text': 'value 1'
},
{
'id': 'imageName',
'text': 'value 1'
}
]
}
Related videos on Youtube
New Bee
Updated on September 16, 2022Comments
-
New Bee over 1 year
I am using select2 with spring mvc. I got the data from my controller that I need to display here in terms of options. But I want them to be grouped as optgroup and also I want images to be appended in it which can be inserted manually as given below : -
<optgroup label="group"> <option value="imageName">value 1</option> <option value="imageName">value 1</option> </optgroup>
Where imageName is the name of image. I want to : 1) Group options in json. 2) Provide this image attribute in json so that select2 can form the data.
Here is the code :
$("#my-select").select2({ data : [ { id : 0, text : 'enhancement' }, { id : 1, text : 'bug' }, { id : 2, text : 'duplicate' }, { id : 3, text : 'invalid' }, { id : 4, text : 'wontfix' } ] });
I am creating my json manually from my objects. So I can provide any data here. Any suggestions ?