How do I limit search paramter only to one column in datatables only when using URL paramter

Viewed 41

I am working on a datatable where I need to limit the search to one column only when using paramater. example:abc.com?search=test. But, if not passing parameter, it should search all columns. How do I achieve this? Here is the code I have. Here is the fiddle: http://live.datatables.net/piquxewa/1/edit

Javascript

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()['search'];
    var table = $('#example1').DataTable( {
      responsive: true,
      paging: false,
      searching: true,
      lengthChange: false,
      bInfo: false,
      bSort: true,
"columnDefs": [
    { "searchable": false, "targets": 0 }
  ],

      search: {
        search: searchTerm
      }
   });
  });

</script>

HTML:

<h2>Datatable 2</h2>

<table id="example1" class="row-border stripe dataTable no-footer dtr-inline" role="grid" style=" width: 100%;"><thead>
<tr role="row">
<th style=" width: 11%;">Date</th>
<th style=" width: 23%;">Name</th>
<th style=" width: 23%;">Type</th>
<th style=" width: 23%;">Topic</th>
<th style=" width: 20%;">Hidden</th>
</tr>

</thead><tbody>
<tr>
<td>Current</td>
<td>John Doe</td>
<td>ABC</td>
<td>Test</td>
<td>orange, banana</td>
</tr>

<tr>
<td>Current</td>
<td>Baby</td>
<td>ABC</td>
<td>Test</td>
<td>orange, banana</td>
</tr>

<tr>
<td>Current</td>
<td>Joe</td>
<td>ABC</td>
<td>Test</td>
<td>orange, banana</td>
</tr>

<tr>
<td>Current</td>
<td>John</td>
<td>ABC</td>
<td>Test</td>
<td>orange, banana</td>
</tr>




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


</html>
1 Answers

If I understood well, you want the searchable option to be set to true for column 0 ONLY IF exists a search term for the search= GET parameter, right?

Otherwise, you want to set it to false.

That's how you can achieve it with a ternary operator:

"columnDefs": [
  { "searchable": searchTerm === undefined ? false : true, "targets": 0 }
  ],
Related