Add options to my Select2

434
November 26, 2016, at 5:43 PM

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?

Answer 1

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;
  }
});
Rent Charter Buses Company
READ ALSO
jQuery UI Selectmenu: customize button view

jQuery UI Selectmenu: customize button view

I know that there is an option to customize view of options by extending _renderItem function in selectmenuIs there a way to place icon fo buttonText like in the following selectmenu options ?

506
Validating dynamically created div using jquery

Validating dynamically created div using jquery

I am adding div dynamically with having multiple input tag to a div having id="lessonDetails"I am trying to validate it with jquery, code is as below :

295
Refresh div on interval

Refresh div on interval

I need to reload some div on a page, I have done some research and most of it said that jQuery is the simplest way to do itBut i've never used jQuery before

427
Boostrap multiselect dropdown coming empty

Boostrap multiselect dropdown coming empty

I am using bootstrap-multiselect for multiselect dropdownHeres my code --

391