I am making a music list with JSON for a search And displaying it as soon as the user enters some text. Here it is:
var music = [
{"name": "Abba"},
{"name": "Justin Bieber"},
{"name": "Taylor Swift"},
{"name": "David Guetta"},
{"name": "Usher"},
{"name": "LMFAO"},
{"name": "Enrique Iglesias"},
{"name": "Pitbull"},
{"name": "Eminem"},
{"name": "Nickelback"},
{"name": "Rihanna"},
{"name": "Queen"},
{"name": "Linkin Park"},
{"name": "Lady Gaga"},
{"name": "Gym Class Heroes"},
{"name": "Maroon 5"},
{"name": "heyhihello"},
{"name": "Paramore"},
{"name": "Owl City"},
{"name": "Black Eyed Peas"},
{"name": "Coldplay"},
{"name": "White Stripes"},
{"name": "Selena Gomez"},
{"name": "Selena Gomez and The Scene"},
{"name": "Creed"},
{"name": "Hinder"}
];
$(document).ready(function(){
sendm = function(txt){
var st = txt.toLowerCase();
if(st.length>0){
var res = new Array();
$.each(music, function(i, item) {
if(item.name.substring(0, st.length).toLowerCase()===st){
res[i] = item.name;
}
});
document.getElementById("main-p").innerHTML = res.join("<br>");
}
};
});
Now if the user enters “Usher”, in the result, it will leave a few lines because of the
tags. How do I remove them?
Change:
To:
Then your array’s length will be the number of matches found instead of the index of the last match found.