Combine Select2 with DataTables?

Hi all,

I’m fetching an Array of JSON Objects with AJAX and present them with DataTables. This has worked nicely as long as these objects weren’t nested, namely like this:

[ {id:'0', name:'x', links:'url0'},
{id:'1', name:'y', links:'url1'},

The problem now is some ‘links’ can have several values, so I want to use for this a Select2 dropdown menu.
I tried several things to do this and the best result so far was to get this:

[object Object]

I have looked many examples but I couldn’t find one similar to my case. I don’t know where should I put the select tag as well as how the JS should look like. I have modified my JSON to the expected format of Select2 and I can see it in the Chrome Console.


<table id="myTable" class="display" width="100%" cellspacing="0">
            <td><select class="select2"></select></td>

My JS:

$(document).ready(function () {
        url: "/json",
        type: "GET",
        dataType: "json",
        .done(function (json) {
                "data": json,
                "columns": [
                    {"data": "id"},
                    {"data": "name"},
                    {"data": "links"}],
                select: true,
                    data: json[10].links

So how can I make Select2 and DataTables work together?

My best guess is that your hard-coded table row with the <select> element is being overwritten when DataTables initializes the table and reconstructs it using the JSON data. So by the time your code tries to initialize the Select2 widget, that <select> element no longer exists in the table.

I think what you need is a custom renderer function for the “links” column (pay attention to the 4th and 5th examples). Your renderer should simply return the “links” value for that row/column if it is a single link. However, if the “links” data contains more than one link then your renderer should instead dynamically create and initialize a Select2 widget containing the links, and return the initialized widget.

hi John, i have a problem using select2 on child of datatable can u check this example
when select is hiding on small screen $(‘select’).select2({tags:true}) are not working