//our table's data const tableData = { 1 : ["Simon ugorji", "simon@gmail.com", "01234", "Germany"], 2 : ["Tony ugorji", "tony@gmail.com", "013234", "Turkey"], 3 : ["Victor ugorji", "victor@gmail.com", "014234", "Germany"], 4 : ["Felix ugorji", "felix@gmail.com", "011234", "Canada"], 5 : ["Jordan ugorji", "jordan@gmail.com", "016234", "Costa Rica"], 6 : ["Henry ugorji", "henry@gmail.com", "0166234", "Belgium"], 7 : ["Frank Sams", "sams@gmail.com", "01234", "Nigeria"], 8 : ["John Doe", "jonny@gmail.com", "0123466", "Australia"], 9 : ["Peter Lamb", "peter@gmail.com", "0123774", "Algeria"], 10 : ["Rodney Human", "human@gmail.com", "0128934", "Ukraine"] } //store table data element const tableDataElem = document.querySelector('#append_data'); //function to build table function buildTable(matchingIDs){ //reset table data tableDataElem.innerHTML = ""; //check if parameter is provided if(typeof matchingIDs === "undefined"){ //our loop index let ind = 0; //our table index let tableInd = 1; //loop through table object while(ind < Object.keys(tableData).length){ //append data using a template literal tableDataElem.innerHTML += ` ${tableInd} ${tableData[tableInd][0]} ${tableData[tableInd][1]} ${tableData[tableInd][2]} ${tableData[tableInd][3]} `; //increment loop index ind++; //increment table index tableInd++; } }else if(matchingIDs.length !== 0){ //check if matchingIDs array is not empty //our loop index let ind = 0; //our table index let tableInd = 1; //loop through matching IDs provided while(ind < matchingIDs.length){ //append data by getting ID of the record and using a template literal tableDataElem.innerHTML+=` ${tableInd} ${tableData[matchingIDs[ind]][0]} ${tableData[matchingIDs[ind]][1]} ${tableData[matchingIDs[ind]][2]} ${tableData[matchingIDs[ind]][3]} `; //increment loop index ind++; //increment table index tableInd++; } }else{ tableDataElem.innerHTML+=` NO DATA FOUND `; } }; buildTable(); //attach event listener document.querySelector('#inp_search').addEventListener('input', function(){ //store the search query let value = this.value.trim(); //check if value is not empty if(value){ //store matching record IDs let matchingIDs = []; //loop index let ind = 1; //loop through the data to find matching text while(ind < Object.keys(tableData).length){ //check if current property contains the search query if(tableData[ind][0].includes(value) || tableData[ind][1].includes(value) || tableData[ind][2].includes(value) || tableData[ind][3].includes(value)){ //store the id of the record matchingIDs.push(ind); } //increment index ind++; } //invoke the function by passing in the matching IDs buildTable(matchingIDs); }else{ //invoke the build table function without providing an argument buildTable(); } })