简体   繁体   中英

Replace table instead of append jquery

I have the following code segment that grabs user input from an HTML form, and then reads a CSV file, and grabs corresponding data to display to my website. If I submit another 'searchTerm' after the initial one in my form, it appends the new row of data from the csv file to the page, and I want it to replace instead. When I try to replace the row however, all my data vanishes.

function submitForm(){
    nameValue = document.getElementById("searchTerm").value;

    //document.getElementById("display-results").innerHTML = nameValue;
    location.href = "#page-3";

    function arrayToTable(tableData) {
        var table = $('<table></table>');
        $(tableData).each(function (i, rowData) {
            var row = $('<tr></tr>');
            
            $(rowData).each(function (j, cellData) {
              if (cellData == nameValue) {
                row.append($('<td>'+rowData[1]+'</td>'));
              }
            });
            table.append(row);
        });
        return table;
    }

    $.ajax({
        type: "GET",
        url: "mainFile.csv",
        success: function (data) {
            parsed = Papa.parse(data).data;
            $('#display-results').append(arrayToTable(Papa.parse(data).data));
        }
    });
}

As you can see in the image, it appends the content rather than replacing the first array.

这是我的代码如何执行的一个简单示例,它附加了一行新数据而不是替换旧数据。

Remember to just replace the table, not the entire display-results element (except the first time you build the table).


if($('#display-results table').length === 0) // append if you haven't built the table yet
  $('#display-results').append(arrayToTable(Papa.parse(data).data));
else
  $('#display-results table').replaceWith(arrayToTable(Papa.parse(data).data));

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM