jane
jane

Reputation: 241

append function appends previous data with the new data

I have the following data from ajax which I am trying to display in a UI's popup :

[{"BadgeImage":"http:\/\/localhost:8666\/web1\/profile\/images\/badge image 2\/1.png"},

{"BadgeImage":"http:\/\/localhost:8666\/web1\/profile\/images\/badge image 2\/beyond.png"},

{"BadgeImage":"http:\/\/localhost:8666\/web1\/profile\/images\/badge image 2\/completionist.png"}]

I am using the below Jquery to display it in the popup :

$.each(data, function(index, value) {
  var $img = $('<img src="' + data[index].BadgeImage + '"/>'); // create the image
  $img.addClass('badge-image'); // add the class .badge-image to it

  $('#imagesofBadges').append($img); // append it
  $('#imagesofBadges .badge-image'); // will fetch all the elements that have the class .badge-image that are inside #imagesofBadges.

});

I am able to display the images .

The problem is everytime I click an element which displays the popup,The images of the previous popup gets appended in the new popup.

I tried using one() which is present in jquery and also tried using a counter as in below codes ,but no luck.

$.each(data, function(index, value) {
  var $img = $('<img src="' + data[index].BadgeImage + '"/>'); // create the image
  $img.addClass('badge-image'); // add the class .badge-image to it
  if (counter <= 0) {
    $('#imagesofBadges').append($img); // append it
    $('#imagesofBadges .badge-image'); // will fetch all the elements that have the class .badge-image that are inside #imagesofBadges.
    counter++;
  }
});

please help me on how to display the images, such that it does not get appended to the previous data of the popup.

Upvotes: 1

Views: 86

Answers (2)

Satpal
Satpal

Reputation: 133403

You need to clear the previous content of the container, You ca use .empty()

Remove all child nodes of the set of matched elements from the DOM.

$('#imagesofBadges').empty();
$.each(data, function(index, value) {
  //Your code
});

Upvotes: 2

Brave Soul
Brave Soul

Reputation: 3620

Try this - .append() will append previous html with new one, .html() will overwrite old html for you

 $('#imagesofBadges').html($img);

Upvotes: 1

Related Questions