I am a newbie in JavaScript. Trying to build a small user interface that searches a list of words when we fire a query into the search box. With that, I want to highlight the matching sub-string of each word in the list box so that the user can see at a glance how the word matches the query. To achieve this target I include highlight function in my code by referring some basic JS tutorials. But due to some mistake, it is not working. Can you please help me. Thanks..!!!
function getFullName(item,index) {
return "<li>"+item.firstname + "<span class='tool-tip'>" +item.lastname+"</span> "+ item.id+"</li>";
}
function myFunction1() {
document.getElementById("demo").innerHTML = persons.map(getFullName);
}
function myFunction() {
var input, filter, ul, li, a, i,count=0;
input = document.getElementById("myInput");
filter = input.value.toUpperCase();
var longWords = persons.filter(function(person){
return person.firstname.toUpperCase().indexOf(filter) > -1
});
var message = "Result:" + longWords.length + " words containing '" + input.value;
document.getElementById("demo").innerHTML=message;
ul = document.getElementById("myUL");
ul.innerHTML= longWords.map(getFullName);
highlight();
}
function highlight(){
var inputText, filter1,innerHTML,index;
inputText = document.getElementById("myInput");
console.log(inputText);
filter1 = inputText.value.toUpperCase();
console.log(filter1);
innerHTML1 = inputText.innerHTML;
console.log(innerHTML1);
index1 = innerHTML1.indexOf(filter1);
if ( index1 >= 0 )
{
innerHTML1 = innerHTML1.substring(0,index1) + "<span class='highlight'>" + innerHTML1.substring(index1,index1+filter1.length) + "</span>" + innerHTML1.substring(index1 + filter1.length);
filter1.innerHTML = innerHTML1;
}
}
here is the CSS file:
.highlight{
font-weight:bold;
color:black;
}