mpdc mpdc - 4 months ago 8
Javascript Question

Searching page content with a partial string from a HTML input value

So I'm trying to implement a basic search functionality on a page. I have a page structured from multiple

<div>
and a search bar
<input>
like so:

<input id="search" type="text">

<div class="panel-flex">
<h4>Title One</h4>
</div>
<div class="panel-flex">
<h4>Title Two</h4>
</div>
<div class="panel-flex">
<h4>Title Three</h4>
</div>


As you type in to the search bar, any
<h4>
that does not contain the current value will be removed from the page. This is my code so far, but I can't find a way of getting a partial search match to happen, only an exact match.

For instance, if you searched
t
then everything would show, but if you searched
th
then only
Title Three
would show.

$(document).ready(function() {
$("#search").on("keyup", function() {
var searchTerm = $(this).val();
$(".panel-flex").each(function() {
$(this).hide();
if ($(this).find("h4").text() == searchTerm) {
$(this).show();
}
});
});
});


I want something that works like PHP's
strpos()
function, and all investigation led me to the JavaScript function
indexOf()
, but attempting to implement that in my code breaks it even more.

$(document).ready(function() {
$("#search").on("keyup", function() {
var searchTerm = $(this).val();
$(".panel-flex").each(function() {
$(this).hide();
if ($(this).find("h4").indexOf(searchTerm) != -1) {
$(this).show();
}
});
});
});

Kld Kld
Answer

You can do that using .filter();

$(document).ready(function() {
    $("#search").on("keyup", function() {
        $('.panel-flex').hide();
        var searchTerm = $(this).val().toLowerCase();
         $('.panel-flex').filter(function(){
              return  $(this).find("h4").text().toLowerCase().indexOf(searchTerm) > -1;
        }).show();
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="search" type="text">

<div class="panel-flex">
    <h4>Title One</h4>
</div>
<div class="panel-flex">
    <h4>Title Two</h4>
</div>
<div class="panel-flex">
    <h4>Title Three</h4>
</div>

Comments