Komal Waseem
Komal Waseem

Reputation: 1127

Remove previous text and display new using javascript innerHTML

I'm taking input from user and then displaying the matching results. So if user types 'a', the following text appears: Football Baseball Fast If user types s after a ('as'). The following text is displayed Football Baseball Fast Baseball Fast. But I want to remove the first 3 results when user types as.

// JavaScript Document

s1= new String()
s2= new String()
var myArray = new Array();

myArray[0] = "Football";
myArray[1] = "Baseball";
myArray[2] = "Cricket";
myArray[3] = "Fast";


function test()  // called on onkeyup()
{
 s1 = document.getElementById('filter').value;
 var myRegex = new RegExp((s1),"ig");
 arraysearch(myRegex);
 }

 function arraysearch(myRegex)
{

for(i=0; i<myArray.length; i++)
{ 
if (myArray[i].match(myRegex))
{
    document.getElementById('placeholder').innerHTML += myArray[i] + "<br/>";
}
}
}

Upvotes: 1

Views: 3308

Answers (3)

ditscheri
ditscheri

Reputation: 579

You need to reset the placeholders innerHTML first. Here's a working example: http://jsfiddle.net/HW6fF/

thePlaceholder = document.getElementById('placeholder');
function arraysearch(myRegex) {
   thePlaceholder.innerHTML = "";
   for(i=0; i<myArray.length; i++) { 
      if (myArray[i].match(myRegex)) {
         thePlaceholder.innerHTML += myArray[i] + "<br/>";
      }
   }
}​

Upvotes: 1

niksvp
niksvp

Reputation: 5563

Add document.getElementById('placeholder').innerHTML=""; as first line to your function arraysearch(myRegex)

Upvotes: 2

Niklas
Niklas

Reputation: 13145

What you're doing is just adding the new list to the old, you're not replacing it. Try replacing the the last for loop with this:

var newHtml;
for(i=0; i<myArray.length; i++)
{
 if (myArray[i].match(myRegex))
 {
     newHtml += myArray[i] + "<br/>";
 }
}
document.getElementById('placeholder').innerHTML = newHtml;

Upvotes: 1

Related Questions