Display multiple columns in Select2

opensas picture opensas · May 15, 2013 · Viewed 30.8k times · Source

I'm using select2 and I'd like to show a multicolum table as a drop down, so I need the width of the drop down container to have a different (larger) width than the input itself

Is it possible to do that?

moreover I'd like to show a table with several columns. From the movies example, I saw that in the formatResult function you create a new table for each row.

Would it be possible to include every row in the same table, so that every cells has the same width? I would need to set some template to contain the rows or something like that.

What I want to achieve is a small input to show the code of an entity, and a large dropdown to show several more columns

--

here's a related issue on github: https://github.com/ivaynberg/select2/issues/1314

Answer

Meloman picture Meloman · Oct 13, 2016

formatresult didn't work for me ! But templateResult works fine like this with data form PHP in HTML generated (not ajax content).

Here is woorking code for me, I seperate my columns by a pipe char (we could have more than 2 columns) :

html (from PHP) :

<option value="...">
    column 1 text | column 2 text
</option>

javascript (jQuery) :

$('#selectSubstance').select2({
    templateResult: function(data) {
        var r = data.text.split('|');
        var $result = $(
            '<div class="row">' +
                '<div class="col-md-3">' + r[0] + '</div>' +
                '<div class="col-md-9">' + r[1] + '</div>' +
            '</div>'
        );
        return $result;
    }
});