Reputation: 846
I have following Html table in my application
<table class="table table-striped table-hover table-bordered" id="sample_editable_1">
<thead>
<tr>
<th>Id</th>
<th>User Name</th>
<th>First Name</th>
<th>Last Name</th>
<th>Phone Number</th>
<th>Gender</th>
</tr>
</thead>
<tbody>
@foreach($user as $users)
<tr>
<td>{{$users['id']}}</td>
<td>{{$users['user_name']}}</td>
<td>{{$users['first_name']}}</td>
<td>{{$users['last_name']}}</td>
<td>{{$users['phone_no']}}</td>
<td>{{$users['gender']}}</td>
@endforeach
</tbody>
</table>
I have wrote following JavaScript for search in this table
<script>
function myFunction() {
var input, filter, table, tr, td, i;
input = document.getElementById("myInput");
filter = input.value.toUpperCase();
table = document.getElementById("sample_editable_1");
tr = table.getElementsByTagName("tr");
for (i = 0; i < tr.length; i++) {
td = tr[i].getElementsByTagName("td")[1];
if (td) {
if (td.innerHTML.toUpperCase().indexOf(filter) > -1) {
tr[i].style.display = "";
} else {
tr[i].style.display = "none";
}
}
}
}
</script>
This particular code is working for single index like td = tr[i].getElementsByTagName("td")[0] or [1] how can i can make it working for a scenario that whatever user search for table should show every thing which is matching with the input?
Upvotes: 0
Views: 901
Reputation: 11809
The same way as you loop your trs, you should loop your tds:
function myFunction() {
var input, filter, table, tr, td, i, ii;
input = document.getElementById("myInput");
filter = input.value.toUpperCase();
table = document.getElementById("sample_editable_1");
tr = table.querySelectorAll("tbody tr");
for (i = 0; i < tr.length; i++) {
var tds = tr[i].getElementsByTagName("td");
var found = false;
for (ii = 0; ii < tds.length && !found; ii++) {
if (tds[ii].textContent.toUpperCase().indexOf(filter) > -1) {
found = true;
break;
}
}
tr[i].style.display = found?"":"none";
}
}
Protips: Keep your indentation clean and textContent
fits better in this scenario.
Don't try to search against tr[i].textContent
as that will concatenate column contents, so if last_name column has "juan" and phone_no column has "0411", searching for "an04" will return positive. I guess that you don't want this to happen. Is better to search for each column content individually.
Upvotes: 1