SalPal
SalPal

Reputation: 11

Dynamically add and remove rows in an HTML table

I have created a drop down table that should delete the existing rows upon selecting something from the drop down while adding new rows.

I am able to add, but I can't figure out how to delete the old ones. Help!

var currencies;

$.ajax({
    url: 'data.json',
    type: "post",
    dataType: "json",
    method: "GET",
    success: function (data, textStatus, jqXHR) {
        currencies = data[0].currencies; 
        drawTable(currencies);
    }
});


function drawTable(currencies) {
    for (var i = 0; i < currencies.length; i++) {
        drawRow(currencies[i]);
    }
}


function IfTheyPicked5Days() {
    if ($("#dropdown")[0].value=="fivedays") {
        return true;
    }
    else {
        return false;
    }  
}

function redrawTableForPeopleWhoPicked1Month() {
    drawTable(currencies);
}

function drawRow(rowData) {
var row = $("<tr />")
$("#currencyhomework").append(row);
row.append($("<td>" + rowData.currency + "</td>"));
row.append($("<td>" + rowData.country + "</td>"));
row.append($("<td>" + rowData.ranges.oneday + "</td>"));

if (IfTheyPicked5Days()){
    row.append($("<td>" + rowData.ranges.fivedays + "</td>"));
} else {
    row.append($("<td>" + rowData.ranges.onemonth + "</td>"));
}

}

Upvotes: 1

Views: 94

Answers (1)

Mouser
Mouser

Reputation: 13304

        function drawTable(currencies) {
            //empty the table here:
             $("#currencyhomework").empty();
            for (var i = 0; i < currencies.length; i++) {
                drawRow(currencies[i]);
            }
        }

Every time when drawTable is called you should empty it. This way every (re)draw of the table starts with updated data. Empty() is jQuery's equivalent of element.innerHTML = null.

Upvotes: 1

Related Questions