Skip to content
Advertisement

How to pass column paramter to datatables search through URL

I have successfully setup datatables with a search parameter to my datatbles table via URL. For example I can prefilter the search term on datatables by using the following URL. abc.html?search=test

However I am not sure how to pass the parameter so that datatable is prefiltered by search term and topic value. Something like abc.com/?topic=my topic

My code shows me 3 results (since it searching my search terms) instead of 2 since there are only two my topics. Please see the code I have on the datatables page below.

http://live.datatables.net/nitozucu/3/edit

JS code:

function getUrlVars() {
          var vars = [], hash;
          var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
          for(var i = 0; i < hashes.length; i++)
          {
              hash = hashes[i].split('=');
              vars.push(hash[0]);
              vars[hash[0]] = hash[1];
          }
          return vars;
      }

$(document).ready(function () {
var searchTerm = getUrlVars()['Topic'];
                var table = $('#myselector').DataTable({

orderCellsTop: true,
responsive: true,
paging: false,
      searching: true,
      lengthChange: false,
      bInfo: false,
search: {
        search: searchTerm
      },
      bSort: true,
                                          
              initComplete: function () {
            this.api().columns().every( function () {
                var column = this;
                var select = $('<select><option value=""></option></select>')
                    .appendTo( $("#myselector thead tr:eq(1) th").eq(column.index()).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 ) {
                    var val = $('<div/>').html(d).text();
select.append( '<option value="' + val + '">' + val + '</option>' );
                } );
            } );
        }
    } );
    });

HTML:

<!DOCTYPE html>
<html>
  <head>
    <script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>

    <link href="https://nightly.datatables.net/css/jquery.dataTables.css" rel="stylesheet" type="text/css" />
    <script src="https://nightly.datatables.net/js/jquery.dataTables.js"></script>

    <meta charset=utf-8 />

  </head>
  <body>
    <table id="myselector" class="row-border stripe dataTable no-footer dtr-inline" role="grid" style=" width: 100%;"><thead>
<tr role="row">
<th class="filterhead">Date</th>
<th class="filterhead">Type</th>
<th class="filterhead">Topic</th>
</tr>

<tr>
<th>Date</th>
<th>Type</th>
<th>Topic</th>
</tr>

</thead><tbody>
<tr>
<td>Current</td>
<td>test</td>
<td>my topic</td>
</tr>

<tr>
<td>Current</td>
<td>test</td>
<td>my topic</td>
</tr>

<tr>
<td>Current</td>
<td>test</td>
<td>ABC</td>
</tr>

<tr>
<td>01/1997</td>
<td>test2</td>
<td>my topic</td>
</tr>

<tr>
<td>10/27/1993</td>
<td>test3</td>
<td>ABC</td>
</tr>



</tbody></table>
</div>

</html>

Advertisement

Answer

Although I personally felt that “input” fields are more suitable than “select/option”:

  1. Need to handle the case sensitivity from the query string variables (I didn’t handle it in the solution below)
  2. Need to decode the URL if your option values has a space or special characters in it.
  3. the query string variable has to be very precise. if your option value=”abc”, your parameter passed has to be topic=”abc”, topic=”ab” wont select anything.

here’s a solution based on your current code

  function getUrlVars() {
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
      hash = hashes[i].split('=');
      vars.push(hash[0]);
      vars[hash[0]] = hash[1];
    }
    return vars;
  }

  $(document).ready(function () {
    //var searchTerm = getUrlVars()['Topic'];
    var topic = decodeURIComponent(getUrlVars()['Topic']);
    var type = decodeURIComponent(getUrlVars()['Type']);
    var date = decodeURIComponent(getUrlVars()['Date']);
    var table = $('#myselector').DataTable({

      orderCellsTop: true,
      responsive: true,
      paging: false,
      searching: true,
      lengthChange: false,
      bInfo: false,
/*      search: {
        search: searchTerm
      },*/
      bSort: true,

      initComplete: function () {
        this.api().columns().every( function () {
          var column = this;
          
          var select = $('<select><option value=""></option></select>')
          .appendTo( $("#myselector thead tr:eq(1) th").eq(column.index()).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 ) {
            var val = $('<div/>').html(d).text();
            select.append( '<option value="' + val + '">' + val + '</option>' );
          } );
          switch(this.header().innerText) {
            case "Topic": select.find("option[value='"+ topic +"']").attr("selected", "selected");
              break;
            case "Type": select.find("option[value='"+ type +"']").attr("selected", "selected");
              break;
            case "Date": select.find("option[value='"+ date +"']").attr("selected", "selected");
              break;
          }
          select.change()
        } );
      }
    } );


  });
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement