DEV Community

Cover image for Simple Search box using JavaScript
Harshita Nahta
Harshita Nahta

Posted on

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>

Enter fullscreen mode Exit fullscreen mode
  • 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);

Enter fullscreen mode Exit fullscreen mode

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>

Enter fullscreen mode Exit fullscreen mode

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)
}

Enter fullscreen mode Exit fullscreen mode

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

Happy Developing!

Top comments (1)

Collapse
 
harshitanahta profile image
Harshita Nahta

Thanks for taking a look and sharing your feedback!