Search code examples
javascripthtmlinnerhtml

InnerHTML Property Appending Instead of Replacing Data


I'm trying to create a real time matched-data displayer. (ie, I have an array of data, when a user enters a string on the text box, the matched strings from the array will be displayed).

But here a small problem occured, when I try to display the new matched-data , the old data is also appending with the result.

for eg, assume that the array is => ['abcd','aaa','bcd','aabb']

I). First I entered the letter 'a'

then the output will be

 - abcd
 - aaa
 - aabb

II). Then I add one more letter 'aa'

Output Expected:

 - aaa
 - aabb

Output Returned By Program:

- abcd
- aaa
- aabb
- aaa
- aabb

Here Is the code

var elemContainer = ['abcd','aaa','bcd','aabb'];
var matchedItems = [];
var result = '';

function showSearchData(){
  document.getElementById('search').addEventListener('keyup',function(){
  /*console.log(this.value);*/
   var data = this.value;
   for(let i=0;i < elemContainer.length; i++){
    if(elemContainer[i].includes(data)){
      matchedItems.push(elemContainer[i]);
    }
   }
   result = '';
   console.log(result);
   displayMatchedData();
  });
}

function displayMatchedData(){
  /*result = '';*/
  document.getElementById('matched-items-container').innerHTML = '';
  for(let i=0;i<= matchedItems.length;i++){
    result += '<li>'+matchedItems[i]+'</li>';
  }
  document.getElementById('matched-items-container').innerHTML = result;
}


showSearchData();
<input type="text" id="search" />
<ul id="matched-items-container"></ul>

What I have tried so far I. Reset the result variable every time whenever a keyup event is happened. II. Set the element.innerHTML to NULL every time the display() is called.


Solution

  • Just clear your matchedItems array every keyup action, also your counter starts from 0 , so this line for(let i=0; i<= matchedItems.length; i++) must be without = or it will give you undefined

    var elemContainer = ['abcd','aaa','bcd','aabb'];
    var matchedItems = [];
    var result = '';
    
    function showSearchData(){
      document.getElementById('search').addEventListener('keyup',function(){
      
      matchedItems = [];
      
       var data = this.value;
       for(let i=0;i < elemContainer.length; i++){
        if(elemContainer[i].includes(data)){
          matchedItems.push(elemContainer[i]);
        }
       }
       result = '';
       console.log(result);
       displayMatchedData();
      });
    }
    
    function displayMatchedData(){
      /*result = '';*/
      document.getElementById('matched-items-container').innerHTML = '';
      for(let i=0;i< matchedItems.length;i++){
        result += '<li>'+matchedItems[i]+'</li>';
      }
      document.getElementById('matched-items-container').innerHTML = result;
    }
    
    
    showSearchData();
    <input type="text" id="search" autocomplete="off" />
    <ul id="matched-items-container"></ul>