I am learning Javascript and am trying to create a run-time search option from a list of data in a table. The data in the table is loaded on runtime and onKeyup I want to show only the rows which matches my condition. Below is a snippet of my code. My problem is during display, all the data gets displayed in the first column. How can I make sure that its displayed correctly.
<html>
<head>
<style>
.child {
border: 1px solid #ff0000;
}
table,tr,td{
border: 1px solid #ff0000;
}
</style>
<script>
var counter =1;
var objList =[];
objList[0]={name:"Nabila", jobId:"123456"};
objList[1]={name:"Partha", jobId:"234567"};
objList[2]={name:"Saurabh", jobId:"345678"};
objList[3]={name:"Nabeela", jobId:"456789"};
function loadData() {
var objTo = document.getElementById("resultantTable");
for(var i = 0; i < objList.length; i++){
var divtest = document.createElement("tr");
divtest.setAttribute("id", counter);
divtest.innerHTML = '<td> ' + counter + ' </td><td>' +
objList[i].name + '</td><td>' + objList[i].jobId + '</td>';
objTo.appendChild(divtest);
counter++;
}
}
function search(){
var edValue = document.getElementById("itemToSearch");
var text = edValue.value;
for(var i=0;i<objList.length;i++){
if((objList[i].name.toUpperCase()).indexOf(text.toUpperCase()) == -1)
document.getElementById(i+1).style.display ='none';
else
document.getElementById(i+1).style.display ='block';
}
}
</script>
</head>
<body onLoad="loadData();">
<div id="list">
<label> Text </label>
<input type="text" id="itemToSearch" onKeyup="search(this);"/>
<input type="button" value="Add" onclick="addToList();" />
</div>
<div id="add">
<div class="divAdd" >
<table id="resultantTable" >
<tr>
<td> SL # </td>
<td> Name </td>
<td> Job id # </td>
</tr>
<tbody></tbody>
</table>
</div>
</div>
</body>
</html>
Just replace the following statement:
document.getElementById(i+1).style.display ='block';
to
document.getElementById(i+1).style.display="table-row";
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.