Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
606 views
in Technique[技术] by (71.8m points)

javascript - Jquery select2 json data with optgroup and images

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 ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...