Jquery select2 json data with optgroup and images

泪湿孤枕 提交于 2019-11-27 23:03:03

问题


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 ?


回答1:


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'
    }
  ]
}


来源:https://stackoverflow.com/questions/31452318/jquery-select2-json-data-with-optgroup-and-images

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!