Martin Martin - 7 months ago 16
HTML Question

JS search using keyup event on input tag

I have few

div
elements with different text content and one
input
tag.

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

<div class="list>
<div id="el"> red </div>
<div id="el"> blue </div>
<div id="el"> red green </div>
</div>


I'd like to get something like this:
if
div
's
textContent
is equal to
input.value
this
div
is displayed. Else, it's hidden.

Example:

input.value = "red"
/* "red" and "red green" are displayed, "blue" is hidden */


My JS code:



var search = document.getElementById("search");
var el = document.getElementById("el");

search.addEventListener("keyup", function(){
if(search.value == el.textContent){
el.style.display = "block"}
else{
el.style.display = "none"}})

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

<div class="list">
<div id="el"> red </div>
<div id="el"> blue </div>
<div id="el"> red green </div>

</div>




Answer

You don't want to assign the same id to multiple items. Instead use class.

See below for a working solution:

var search = document.getElementById("search");
var els = document.querySelectorAll(".el");

search.addEventListener("keyup", function() {

  Array.prototype.forEach.call(els, function(el) {
    if (el.textContent.trim().indexOf(search.value) > -1)
      el.style.display = 'block';
    else el.style.display = 'none';
  });

});
<input id="search" type="text" />

<div class="list">
  <div class="el">red</div>
  <div class="el">blue</div>
  <div class="el">red green</div>

</div>

Comments