I’m trying to make a filterable table like this one. That is, to render the existing table filterable. I copied the code on the w3schools website, but it doesn’t work. I type text, but nothing gets filtered
<div id="users-table" class="tab-pane container active table-responsive">
<input class="form-control" id="my-search-input" type="text" placeholder="Search...">
<table class="table table-hover text-center">
<thead class="table-dark">
<tr>
<!-- headings -->
</tr>
</thead>
<tbody id="table-body">
<!-- table body and the rest -->
<script>
$(document).ready(function(){
$("#my-search-input").on("keyup", function() {
let value = $(this).val().toLowerCase();
$("#table-body tr").filter(function() {
$(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
});
});
});
</script>
<!-- JS imports -->
</body>
Initially, I had these JS imports
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"
integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo"
crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"
integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1"
crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"
integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM"
crossorigin="anonymous"></script>
Then I tried replacing them with the imports they had on w3 (should I have clean-installed after that?)
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.slim.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
I also tried moving the script around
What’s the problem and how do I make my search field work and filter the rows of my table as intended?
2
Answers
I realized that my JQuery import has to be before my
<script>
that utilizes JQuery. If I place the<script>
after the JQuery import, it works fine. Rookie mistake!To make it work, the only script needed is jQuery (full or slim).
We have to add the jQuery library to our webpages inside the head tag at the top, before any other libraries since there are many libraries depends on it like bootstrap and popper.