I am trying to implement a search feature which enables the user to search through this table which is being populated from a JSON from a public api.
My table:
<input type="text" id="myInput" onkeyup="searchPlayers()" placeholder="Search for player">
<table id ="player_info">
<tr>
<th>ID</th>
<th>Full Name</th>
<th>Team</th>
<th>Position</th>
<th>Current Price</th>
<th>Value Season</th>
<th>Cost Change from Start</th>
<th>Percentage selected by</th>
<th>Transfers In</th>
<th>Transfers Out</th>
<th>Total Points</th>
<th>Points Per Game</th>
<th>Minutes</th>
<th>Goals Scored</th>
<th>Assists</th>
</tr>
Populating the table from the JSON. Iterating through the JSON file and create a new table cell for each of the keys.
request.onload = function() {
// Begin accessing JSON data here
var data = JSON.parse(this.response);
if (request.status >= 200 && request.status < 400) {
var table = document.getElementById('player_info');
data.elements.forEach(elements => {
var tr = document.createElement('tr');
tr.innerHTML = '<td>' + elements.id + '</td>' +
'<td>' + elements.first_name + '<p>' + '</p>' + elements.second_name + '</td>' +
'<td>' + elements.team_code + '</td>' +
'<td>' + elements.element_type + '</td>' +
'<td>' + elements.now_cost + '</td>' +
'<td>' + elements.value_season+ '</td>' +
'<td>' + elements.cost_change_start + '</td>' +
'<td>' + elements.selected_by_percent + '</td>' +
'<td>' + elements.transfers_in + '</td>' +
'<td>' + elements.transfers_out + '</td>' +
'<td>' + elements.total_points + '</td>' +
'<td>' + elements.points_per_game + '</td>' +
'<td>' + elements.minutes + '</td>' +
'<td>' + elements.goals_scored + '</td>' +
'<td>' + elements.assists + '</td>';
table.appendChild(tr);
});
}
//append_json(data);
console.log(data);
}
Search for players function
function searchPlayers() {
// Declare variables
var input, filter, table, tr, td, i, txtValue;
input = document.getElementById("myInput");
filter = input.value.toUpperCase();
table = document.getElementById("player_info");
tr = table.getElementsByTagName("tr");
// Loop through all table rows, and hide those who don't match the search query
for (i = 0; i < tr.length; i++) {
td = tr[i].getElementsByTagName("td")[0];
if (td) {
txtValue = td.textContent || td.innerText;
if (txtValue.toUpperCase().indexOf(filter) > -1) {
tr[i].style.display = "";
} else {
tr[i].style.display = "none";
}
}
}
}
Does anybody know why this is not working?