Simple Search box using JavaScript

Simple search operation using JavaScript to filter out the items from list. so we have … Read more Simple Search box using JavaScript

Simple search operation using JavaScript to filter out the items from list.

so we have a search box here and an unordered list with 0 child items.

<div class="center">
<textarea rows="1" name="searchBox" id="searchBox" placeholder="Type to search"></textarea>
<i class="material-icons">search</i>
</div>
<ul class="center" id="list">
<ul>

  • add elements to the list using DOM Manipulation
var list= ["banana" , "strawberry" , "orange" , "apple"]

var listEle = document.getElementById("list");

insertListItems = (tempList) => {
   listEle.innerHTML = "";
   tempList.map((i)=>{
      var liEle = document.createElement("LI");
      var liText = document.createTextNode(i);          
      liEle.appendChild(liText);  
      listEle.appendChild(liEle);
   })
}

insertListItems(list);

now add onkeyup event in textarea to call the search function on entering any value in textarea

<textarea onkeyup="search(this.value)"  placeholder=" type to search" rows="1" name="searchBox" id="searchBox"></textarea>

the function takes search value as parameter and checks if the search value is not empty if it is empty it simply uses the same data , else using the filter method we can filter out values accordingly

Note : toUpperCase method is used so that search results are not case sensitive.

search = (searchTerm) => {
  searchTerm = searchTerm.toUpperCase()
  var temp = list;
  if(searchTerm != ""){
      listEle.innerHTML = "";
      temp = list.filter((i)=>{
        i = i.toUpperCase()
        if( i.indexOf(searchTerm) != -1){
           return i
        }})
    }
     insertListItems(temp)
}

Link for reference :-
https://codepen.io/harshita-nahta/pen/NWvrYWB

Happy Developing!

Source: DEV Community



Leave a Reply

Your email address will not be published. Required fields are marked *