Datatables functionality
Getting selected data from outside a datatable
HTML
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<script src="//cdn.datatables.net/1.10.7/js/jquery.dataTables.min.js"></script>
<link rel="stylesheet" href="//cdn.datatables.net/1.10.7/css/jquery.dataTables.css">
<input type="text" id="txtIn" placeholder="Enter ID"/><button id="filterButton" class="btn btn-primary">Search</button>
<table id="example" class="table">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Age</th>
</tr>
</thead>
<tbody>
<tr>
<td>tig001</td>
<td>Tiger Nixon</td>
<td>System Architect</td>
<td>Edinburgh</td>
<td>61</td>
</tr>
<tr>
<td>gar001</td>
<td>Garrett Winters</td>
<td>Accountant</td>
<td>Tokyo</td>
<td>63</td>
</tr>
<tr>
<td>ash001</td>
<td>Ashton Cox</td>
<td>Technical Author, Junior</td>
<td>San Francisco</td>
<td>66</td>
</tr>
</tbody>
</table>
CSS
.btn {
margin: 20px;
}
JavaScript
$(function () {
var dataTable = $('#example').DataTable({
searching: true,
});
$('#filterButton').on('click', function () {
var searchCode = $("#txtIn").val();
var dataTable = $('#example').DataTable();
var names = dataTable.rows( function (idx, data, node) {
return data[0] == searchCode ? true : false;
});
if (names.data().length == 1) {
// have a match, want to get the position
// I can get the entire row:
alert("Matched row info: "+names.data()[0]);
// but I don't know how to get just the position (column 2) for this matched row.
// I thought the below would work, but it's not just looking at the matched row.
alert(searchCode+" position should be "+names.data().column(2).data()[0]);
// above line always gives column 2 row 0 information, regardless of match.
// so if you entered tig001, the alert above says "Technical Author, Junior"
} else {
// no match for ID
alert("No match: "+searchCode+" was not an ID in the table.");
}
});
});