Reputation: 417
I have an html document with the following section:
<select id="avgSalesTable" onchange="createTable();">
<option>---</option>
<option value="2018">2018</option>
<option value="2016">2016</option>
</select>
And I have a JavaScript file with the following section:
function createTable(year) {
var filtered_year = document.getElementById("avgSalesTable").value;
console.log(filtered_year)
var filtered_data = realEstateData.filter(x => x.year === filtered_year)
console.log(filtered_data)
for (var i = 0; i < filtered_data.length; i++) {
var row = d3.select('tbody').append('tr');
row.append('td').html(filtered_data[i].Borough);
row.append('td').html(filtered_data[i].averagePrice1familyHome);
}
}
createTable(2016)
I want the table to change as a new selection in the dropdown menu is made. However, the result that I am getting is that new rows are appended to the previous table.
Here is the realEstateData file:
var realEstateData = [
{
year: "2018",
Borough: "Bronx",
averagePrice1familyHome: 499060
},
{
year: "2016",
Borough: "Bronx",
averagePrice1familyHome: 478379
},
//--------------
{
year: "2018",
Borough: "Manhattan",
averagePrice1familyHome: 8235346
},
{
year: "2016",
Borough: "Manhattan",
averagePrice1familyHome: 8176576
},
//--------------
{
year: "2018",
Borough: "Brooklyn",
averagePrice1familyHome: 980737
},
{
year: "2016",
Borough: "Brooklyn",
averagePrice1familyHome: 876864
},
//--------------
{
year: "2018",
Borough: "Queens",
averagePrice1familyHome: 645921
},
{
year: "2016",
Borough: "Queens",
averagePrice1familyHome: 613139
},
//--------------
{
year: "2018",
Borough: "Staten Island",
averagePrice1familyHome: 520214
},
{
year: "2016",
Borough: "Staten Island",
averagePrice1familyHome: 483340
},
//--------------
];
Thank you in advance
Upvotes: 1
Views: 454
Reputation: 7403
d3
is not used as it should in the existing code: d3's data join
feature is not used, it would provide the benefit of facilitating the management of changes in the data.
A quick fix is to empty the table before appending rows. This can be done by adding the following right before the for
loop:
d3.select('tbody').html('')
Otherwise, the code should be refactored, main steps being:
selection.data()
selection.join()
to update the table as wanted: add new relevant rows, remove obsolete rows.createTable
to updateTable
(nice to have)Upvotes: 1