delano delano - 1 month ago 6
Javascript Question

Search function filter li's in pure Js

I'm trying to make an input that filters a

<ul>
based on the value in pure JavaScript. It should filter dynamically with the onkeyup by getting the li's and comparing their inner element name with the filter text.

Here is my function:

var searchFunction = function searchFeature (searchString) {
console.log("Is my search feature working?");
//Get the value entered in the search box
var inputString = document.getElementById('inputSearch');
var stringValue = inputString.value;
//Onkeyup we want to filter the content by the string entered in the search box
stringValue.onkeyup = function () {
//toUpperCase to make it case insensitive
var filter = stringValue.toUpperCase();
//loop through all the lis
for (var i = 0; i < eachStudent.length; i++) {
//Do this for all the elements (h3, email, joined-details, date)
var name = eachStudent[i].getElementsByClassName('student-details')[1].innerHTML;
//display all the results where indexOf() returns 0
if (name.toUpperCase().indexOf(filter) == 0)
eachStudent[i].style.display = 'list-item';
else
eachStudent[i].style.display = 'none';
}
}}


My HTML for the search bar:

<div class="student-search">
<input id="inputSearch" placeholder="Type name here.." type="text"> <button>Search</button></div>


My HTML for one of the li's:

<ul class="student-list">
<li class="student-item cf">
<div class="student-details">
<img class="avatar" src="#">
<h3>John Doe</h3>
<span class="email">John.Doe@example.com</span>
</div>
<div class="joined-details">
<span class="date">Joined 01/01/14</span>
</div>
</li>


I would like to filter all the elements (name, email, joined date) based on the value of the input.
Unfortunately, I don't get any errors and it's simply not working.
The function is correctly invoked because the console.log prints...

Here goes the codepen: http://codepen.io/Delano83/pen/qaxxjA?editors=1010

Any help or comments on my code is very appreciated.

Answer

There were several issues:

  • stringValue.onkeyup - stringValue is the value. You can't onkeyup it.
  • var eachStudent = document.querySelector(".student-item"); will fetch the first thing with student-item class. You need to use querySelectorAll or just use jquery's $('.find-item').
  • if (name.toUpperCase().indexOf(filter) == 0) indexOf returns 0 if the filter is found at the beginning of the name. 0 as match if found at index 0. You need to check against -1, which means it was not found at all.

Otherwise it more or less worked, good job.

I also added Jquery for me to fix it faster. If you insist on using pure javascript I am sure you will be able to edit it.

Check it out here: http://codepen.io/anon/pen/WGrrXW?editors=1010. Here is the resulting code:

var page = document.querySelector(".page");
var pageHeader = document.querySelector(".page-header");
var studentList = document.querySelector(".student-list");
var eachStudent = document.querySelectorAll(".student-item");
var studentDetails = document.querySelector(".student-details");


//Recreate Search Element in Js
var searchBar = function createBar(searchString) {

    var studentSearch = document.createElement("div");
    var input = document.createElement("input");
    var searchButton = document.createElement("button");

    input.type = "text";

    var txtNode = document.createTextNode("Search");
    if (typeof txtNode == "object") {
        searchButton.appendChild(txtNode);
    }

    studentSearch.setAttribute("class", "student-search");
    input.setAttribute("id", "inputSearch");

    //append these elements to the page
    studentSearch.appendChild(input);
    studentSearch.appendChild(searchButton);

    input.placeholder = "Type name here..";

    return studentSearch;
}

var searchFunction = function searchFeature(searchString) {
    console.log("Is my search feature working?");
    //Get the value entered in the search box
    var inputString = document.getElementById('inputSearch');
    var stringValue = inputString.value;
    //Onkeyup we want to filter the content by the string entered in the search box

    inputString.onkeyup = function() {
            //toUpperCase to make it case insensitive
        var filter = $(this).val().toUpperCase()
        //loop through all the lis 
        for (var i = 0; i < eachStudent.length; i++) {
            //Do this for all the elements (h3, email, joined-details, date)
            var name = $(eachStudent[i]).find('h3').text()
      console.log(name, filter, name.toUpperCase().indexOf(filter))
            //display all the results where indexOf() does not return -1
            if (name.toUpperCase().indexOf(filter) != -1)
                eachStudent[i].style.display = 'list-item';
            else
                eachStudent[i].style.display = 'none';
        }
    }
}

function addElements() {
    console.log('Add search bar, trying to anyway...')
    pageHeader.appendChild(searchBar());
    // page.appendChild(paginationFilter());
    onLoad();
}

window.onload = addElements;
window.onLoad = searchFunction;