Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grouping results in Select2

Is it possible somehow to group results in a Select2 component when it's not using <select> tag, but <input type="hidden">, and results are provided as "data" option in configuration object?

var select2Options = {
  data: {
    results: myArrayOfResults
  }
};
like image 438
the.ufon Avatar asked Jul 12 '13 09:07

the.ufon


People also ask

How do I add options in Select 2?

New options can be added to a Select2 control programmatically by creating a new Javascript Option object and appending it to the control: var data = { id: 1, text: 'Barn owl' }; var newOption = new Option(data. text, data.id, false, false); $('#mySelect2'). append(newOption).

How do I render Select2 options in HTML?

The key here for me is to build a data array with content for both templateSelection and templateResult . The latter renders fine in the dropdown but any multiline content will not be contained in the select2 element so needs to be displayed inline (or at least on a single line).

What is data Select2 ID?

Select2 requires that the id property is used to uniquely identify the options that are displayed in the results list. If you use a property other than id (like pk ) to uniquely identify an option, you need to map your old property to id before passing it to Select2.


1 Answers

Yes, the results objects support a children attribute...

so for example:

var select2Options = {
  data: {
    results: [
      {text: "My shiny group", children: [
          {id: 1, text: "My shiny item"}, 
          {id: 2, text: "My shiny item2"}
      ]}
    ]
  }
};
like image 110
the.ufon Avatar answered Oct 09 '22 10:10

the.ufon