Izzy
Izzy

Reputation: 6866

add items once to table

I have an upload control which is hit each time a file has been successfully uploaded. Users can uploaded 1 or more files at any time. And the following js funciton is called function OnFileUploadComplete(s, e){}. In this function a make an ajax call and get a List<T> of values. I want to loop over the result set from my ajax reponse and display them into a table which I've achieved by doing the following

function successCallBack(result) {
  var table = $("#attachments-table");

  $.each(result.Attachment, function (index) {
      var base64String = btoa(String.fromCharCode.apply(null, new Uint8Array(result.Attachment[index].Thumbnail)));
       var rows = $('<tr></tr>'),
           button = $('<input class="btn btn-danger delete-attachment">').attr({
                  type: 'button',
                  id: result.Attachment[index].Id,
                  name: result.Attachment[index].Id,
                  value: result.Attachment[index].Id });

            rows.append('<td>' + result.Attachment[index].AttachmentName + '</td>');
            rows.append('<td><img class="img-responsive" src="data:image/png;base64,' + base64String + '"></td>');
            $('<td></td>').html(button).appendTo(rows);
            table.append(rows);
  });
}

This works fine to a point. However, If I have multiple items it adds them over and over. So my question is how can only add items which are not already in the table.

Note: The table is empty when the page loads and is filled by the ajax response data

Upvotes: 0

Views: 34

Answers (1)

subrahmanya bhat
subrahmanya bhat

Reputation: 598

try something like this

    function successCallBack(result) {
  var table = $("#attachments-table");

  $.each(result.Attachment, function (index) {
      var base64String = btoa(String.fromCharCode.apply(null, new Uint8Array(result.Attachment[index].Thumbnail)));
       var rows = $('<tr></tr>'),
           button = $('<input class="btn btn-danger delete-attachment">').attr({
                  type: 'button',
                  id: result.Attachment[index].Id,
                  name: result.Attachment[index].Id,
                  value: result.Attachment[index].Id });

            rows.append('<td>' + result.Attachment[index].AttachmentName + '</td>');
            rows.append('<td><img class="img-responsive" src="data:image/png;base64,' + base64String + '"></td>');
            $('<td></td>').html(button).appendTo(rows);
 if($("#"+id).length==0){
            table.append(rows);}
  });
}

Upvotes: 1

Related Questions