How can I use a select2 selectbox with dataTables?
Asked Answered
P

2

6

I want to use a select2 selectbox inside my bootstrap datatable. I need to use the full select2 js But it is not working and I am wondering why.

$(document).ready(function() {
    var table = $('#example').DataTable( {
        scrollY:        "300px",
        scrollX:        true,
        scrollCollapse: true,
        paging:         false,
        fixedColumns:   {
            leftColumns: 1,
            rightColumns: 1
        }
    } );
} );

$("#e1").select2();
td, th{background-color:white;}
<link href="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet"/>

<link href="http://cdnjs.cloudflare.com/ajax/libs/select2/3.2/select2.css" rel="stylesheet"/>

<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://cdn.datatables.net/1.10.15/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/fixedcolumns/3.2.2/js/dataTables.fixedColumns.min.js"></script>

<script src="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>


<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.full.js"></script>


<table id="example" class="stripe row-border order-column" width="100%" cellspacing="0">
        <thead>
            <tr>
                <th>First name</th>
                <th>Last name</th>
                <th>Position</th>
                <th>Office</th>
                <th>Age</th>
                <th>Start date</th>
                <th>Salary</th>
                <th>Extn.</th>
                <th>E-mail</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td><select  id="e1">
        <option value="AL">Alabama</option>
        <option value="Am">Amalapuram</option>
        <option value="An">Anakapalli</option>
        <option value="Ak">Akkayapalem</option>
        <option value="WY">Wyoming</option>
    </select></td>
                <td>Satou</td>
                <td>Accountant</td>
                <td>Tokyo</td>
                <td>33</td>
                <td>2008/11/28</td>
                <td>$162,700</td>
                <td>5407</td>
                <td>[email protected]</td>
            </tr>
        </tbody>
    </table>
Poesy answered 5/7, 2017 at 13:48 Comment(0)
C
12
  1. You are using a CSS 3.2 version along with a 4.0.3 version of the libray! Since version 4 is a complete rewrite any UI will fail. Find matching versions here.

  2. You need to instantiate select2 after dataTables is initialised. You can do that in the drawCallback callback.

  3. Do not use id's to reference the select2's. I guess you will have a lot of select2's on multiple pages, so give them a dummy class like dt-select2 so you can initialise all visible select2's in one call. But by all mean preserve the id's for reference in event handlers.

Example :

$('#example').DataTable({
  ...
  drawCallback: function() {
     $('.dt-select2').select2();
  }
})  

demo

Cureton answered 6/7, 2017 at 8:8 Comment(2)
hey @peace_love, what do you mean by "the toolbar"?Cureton
@Poesy You must target the specific element, try with $('.dataTables_length select').select2() instead -> jsfiddle.net/349kL0puCureton
H
1

See this example include a select option on a header to filter the data:

demo here

$('#example').DataTable({
  initComplete: function() {
    this.api().columns('.fName').every(function() {
      var column = this;
      var select = $('<select class="f"><option value="">First Name</option></select>')
        .appendTo($(column.header()).empty())
        .on('change', function() {
          var val = $.fn.dataTable.util.escapeRegex(
            $(this).val()
          );

          column
            .search(val ? '^' + val + '$' : '', true, false)
            .draw();
        });

      column.data().unique().sort().each(function(d, j) {
        select.append('<option value="' + d + '">' + d + '</option>')
      });
    });
    this.api().columns('.lName').every(function() {
      var column = this;
      var select = $('<select class="f"><option value="">Last Name</option></select>')
        .appendTo($(column.header()).empty())
        .on('change', function() {
          var val = $.fn.dataTable.util.escapeRegex(
            $(this).val()
          );

          column
            .search(val ? '^' + val + '$' : '', true, false)
            .draw();
        });

      column.data().unique().sort().each(function(d, j) {
        select.append('<option value="' + d + '">' + d + '</option>')
      });
    });
  }


})
$(document).ready(function($) {
  $('.f').select2();
});
Hotfoot answered 4/3, 2019 at 10:46 Comment(2)
demo is super! thank you @Glorfindel is there a way to add a select2 to all columns? not just on first and last name?Preussen
@WallaboutProgramming The only thing I did to this answer is have my script fix the broken link, I haven't even read it. The author hasn't been active since they wrote this answer, so I think you'd better ask a new question.Termite

© 2022 - 2024 — McMap. All rights reserved.