Search code examples
lightswitch-2013

LightSwitch Refresh a JScript table instead of appending rows


VS2013 Lightswitch. JScript Calls WepAPI to get a set of date dependent data. JScript creates table and populates it with the data.

Changing of Date control (not shown) causes a new call on the Web API and this data is then appended to the existing data. I am trying to overwrite the data not append it. Assuming this code (which basically is copied), is the right way to go then I need to clear the table prior to the writing of the rows. Quite happy to change technique if I am doing it the wrong way altogether. This is my first LightSwitch project.

function generateList(element, currentItem) {
//debugger; 
//var readingListApi = "../Controllers/TTReading?id=" + _contentListItem.screen.Installation1.id + "&startDate=" + _startListDate + "&endDate=" + _endListDate;
var readingListApi = "../Controllers/TTReading?id=" + currentItem.screen.Installation1.id + "&startDate=" + _startListDate + "&endDate=" + _endListDate;
var myTable = $('<table class="ui-responsive table-stroke" data-role="table" />');
var myHeader = $('<thead><tr><th>Volume</th><th>Flow</th><th>Read Date</th></tr></thead>');
var myBody = $('<tbody/>');
myTable.appendTo($(element));

//myHeader.appendTo($(myTable));
//myBody.appendTo($(myTable));
$.getJSON(readingListApi,
    function(data) {
        //var items = [];
        //debugger; 
        if (data.length > 0 && data.length<1000000) {

            $("#myTable tr").remove();
            myHeader.appendTo($(myTable));
            myBody.appendTo($(myTable));
            $.each(data, function (key, val) {

                var myRow = $("<tr/>");
                $("<td/>").text(val.volume).appendTo($(myRow));
                $("<td/>").text(val.flow).appendTo($(myRow));
                $("<td/>").text(val.read_date_part).appendTo($(myRow));

                myRow.appendTo($(myTable));
            });
            // var itemLength = items.length;
        } else if (data.length == 0) {
            var myEmptyRow = $("<tr/>");
            $("<td/>").text("Empty Period").appendTo($(myEmptyRow));
            myEmptyRow.appendTo($(myTable));
        } else {
            var myTooMuchDataRow = $("<tr/>");
            $("<td/>").text("Too Much Data. Reduce Date Range").appendTo($(myTooMuchDataRow));
            myTooMuchDataRow.appendTo($(myTable));
        }
    });

};


Solution

  • Solved it with some help from google. Proved with Firebug that it was writing a new table each time. So the solution was to give the table an id say readTable then

    var tbl = document.getElementById("readTable");
        if (tbl) tbl.parentNode.removeChild(tbl);
    

    before the append logic.