简体   繁体   中英

Add options to my Select2

I have one problem. I use Select2 in my page, and I would like to modify it a little. This is my example:

<select id="mySelect" multiple>
    <!-- -->
</select>
var data = [{
    id: 1, 
    text: "sample_1", 
    version: "1"
},{
    id: 2, 
    text: "sample_2", 
    version: "2"    
}]

$("#mySelect").select2({
    data: data
});

JSFIDDLE example

In this example displays the text from the downloaded JSON. But what if I wanted a to modify the search? When entering text, it appears next to a third value version with JSON, but if I click on value version will not add to select .

Eg. When i Search in select, my select looks like:

- text_1 - "version"
- text_2 - "version"

but if I click some option, for example text_1 , that only adds to the select box text_1 no version , that is, as far. I think that the example of Templating shows a bit of my problem. Only when you click, for example, in Alaska flag disappears and the text remains in the select

Any suggestions how I can do this?

With templateSelection and templateResult you can control both the search results and the view of selected item

$("#mySelect").select2({
  data:data,
  templateSelection: function(val) {
    return val.text +" - " + "version" + val.version;
  },
  templateResult: function(val) {
    return val.text +" "+ val.version;
  }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM