I am not good in javascript as I am still trying to learn it. I've been trying to populate a table with search results but it seems impossible for me to do at the moment after several tries. I want to search through an object to get user data.
For example, if I search for "foo" through a event generated/dynamic textbox, i'll get the entire result set of all of them since firstName has "foo" in it. Doesn't matter which field. If I search for "foobar", I'll get only the first object since its email value has "foobar" substing. How do I implement this?
I have an object stored in a variable with 3 objects with properties
var usersList =[
{
"firstName": "foo",
"lastName": "bar",
"email": "foobar@gmail.com",
"password": "12345",
"userLevel": "Admin", // manager
"seatId": "PIC3FA1-3",
"localNumber": "777-78-90",
"projects": "Delta, Google"
},
{
"firstName": "foot",
"lastName": "barn",
"email": "footbarn@gmail.com",
"password": "12345",
"userLevel": "Manager", // manager
"seatId": "PIC3FA1-1",
"localNumber": "777-66-12",
"projects": "Kokey, Cathay"
},
{
"firstName": "food",
"lastName": "bard",
"email": "foodbard@gmail.com",
"password": "12345",
"userLevel": "user", // manager
"seatId": "PIC3FA1-21",
"localNumber": "777-78-90",
"projects": "Kokey, Cathay"
}
];
$(".section-dashboard").on('click','.search-column>a', function() {
var input = $(".search-column>input[type='text']").val();
var result = search(input, usersList);
for(var key in result) {
$(".search-column>table>tbody").append('<tr>'
+' <td>'+users[key].firstName+' '+users[key].lastName+'</th>'
+' <td>'+users[key].seatId+'</th>'
+' <td>'+users[key].localNumber+'</th>'
+' <td>'+users[key].projects+'</th>'
+'</tr>');
}
});
function search(input, users) {
var results = [];
for(var i=0; i<users.length; i++) {
for(key in users[i]) {
if(users[i][key].indexOf(input)!=-1) {
results.push(users[i]);
}
}
}
return results;
}
Search results are outputting the correct ones, but often not resembling the search inquiry at all.
Appending it seems to add the new table rows just fine, but how do I make the previous results disappear when searching anew?