Meikel Rizky Hartawan
Meikel Rizky Hartawan

Reputation: 39

Search Box datatable outside the table

i'm trying to create search box datatables outside the table, i'm using datatables version 1.12.1, i use the reference from website and it won't work, the search box is not working.

The result:

enter image description here

oTable = $('#example').dataTable();
$('#myInputTextField').keyup(function() {
  oTable.search($(this).val()).draw();
})
<script src="https://code.jquery.com/jquery-3.5.1.js"></script>
<script src="https://cdn.datatables.net/1.12.1/js/jquery.dataTables.min.js"></script>

<link rel="stylesheet" href="https://cdn.datatables.net/1.12.1/css/jquery.dataTables.min.css">
<input type="text" id="myInputTextField">

<table id="example" class="display" style="width:100%">
  <thead>
    <tr>
      <th>Name</th>
      <th>Position</th>
      <th>Office</th>
      <th>Age</th>
      <th>Start date</th>
      <th>Salary</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Tiger Nixon</td>
      <td>System Architect</td>
      <td>Edinburgh</td>
      <td>61</td>
      <td>2011-04-25</td>
      <td>$320,800</td>
    </tr>
    <tr>
      <td>Foo bar</td>
      <td>Engineer</td>
      <td>Glasgow</td>
      <td>45</td>
      <td>2012-05-26</td>
      <td>$100,800</td>
    </tr>
  </tbody>
</table>

Upvotes: 0

Views: 1714

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337560

To get a reference to the datatable instance you need to use DataTable() - not dataTable(). The latter provides a jQuery object.

I would also suggest using the input event for the search box as it allows users to input text any possible way, not just using the keyboard.

let oTable = $('#example').DataTable();

$('#myInputTextField').on('input', function() {
  oTable.search($(this).val()).draw();
})
<script src="https://code.jquery.com/jquery-3.5.1.js"></script>
<script src="https://cdn.datatables.net/1.12.1/js/jquery.dataTables.min.js"></script>

<link rel="stylesheet" href="https://cdn.datatables.net/1.12.1/css/jquery.dataTables.min.css">
<input type="text" id="myInputTextField">

<table id="example" class="display" style="width:100%">
  <thead>
    <tr>
      <th>Name</th>
      <th>Position</th>
      <th>Office</th>
      <th>Age</th>
      <th>Start date</th>
      <th>Salary</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Tiger Nixon</td>
      <td>System Architect</td>
      <td>Edinburgh</td>
      <td>61</td>
      <td>2011-04-25</td>
      <td>$320,800</td>
    </tr>
    <tr>
      <td>Foo bar</td>
      <td>Engineer</td>
      <td>Glasgow</td>
      <td>45</td>
      <td>2012-05-26</td>
      <td>$100,800</td>
    </tr>
  </tbody>
</table>

Upvotes: 1

Related Questions