Adjusting JS Live Search to show results regardless of word order

147 Views Asked by At

I created a simple javascript live search & disappear to filter names from a list, but now I'm running into trouble when someone searches for "John Smith" and can't find him because he's in the list as "John H. Smith". Is there anything I can add to the js code to have the search look for the input's contents regardless of word order or if there's a middle initial or middle name between the first name and last name?

Codepen for reference: https://codepen.io/naomimekeel/pen/rNzoeGQ

View the live page example: https://www.giveto.pitt.edu/s/1729/18/interior-giving.aspx?sid=1729&gid=2&pgid=5065

<div class="facstaffsearchbar">
    <input type="text"
           id="facstaff-search"
           name="facstaff-search"
           rel="facstaff-search"
           placeholder=" Search for a donor on this list . . ." />
        <div id="none">Sorry, no results found! Please check your spelling or try again.</div>

    <div rel="facstaff-data" id="facstaff-data">
        <div class="facstaff-data-item">+Terry Laughlin KGSB ’81 & Regina L. Aldisert</div>
<div class="facstaff-data-item">+Dr. W. Harry Archer, DEN ’27, A&S ’37 & +Mrs. Louise E. Archer, A&S ’27</div>
<div class="facstaff-data-item">+Lauren H. Ashe, A&S ’14</div>
</div>
let foundOne = false;
const none = document.getElementById('none');
const searchInput = document.querySelector('input[rel="facstaff-search"]');
const data = document.querySelectorAll(".facstaff-data-item");
show(false);
searchInput.addEventListener('input', function (event) {
    // reset state
    show(false)
    foundOne = false;
    const input = event.target
    if (input.value) {
        const toMatch = input.value.toLowerCase();
        for (let i = 0, len = data.length; i < len; i++) {
            const match = data[i].innerHTML.toLowerCase().includes(toMatch);
            data[i].style.display = match ? 'block' : 'none';
            if (match) foundOne = true;
        }
        if (!foundOne) show(true);
    } else 
        resetState()

});
function resetState() {
    for (let i = 0, len = data.length; i < len; i++)
        data[i].style.display = 'block';
    
}
function show(bool) {
    none.style.display = bool ? 'block' : 'none';
}
0

There are 0 best solutions below