Edwin Bossman
Edwin Bossman

Reputation: 91

Data is duplicated when click again in button in javascript

I'm able to display all data, but when I click again in My team the data is displayed twice. Clicking again and again means more times the data is displayed. How can I display data once? I mean just the 6 team members and no 6 team members repeated.

  function myFunction() {
    var popup = document.getElementById("myPopup");
    popup.classList.toggle("show");

    var data1 = "TEAMSEARCH";
    $.ajax({
      url: 'TeamAssignment',
      type: 'POST',
      data: {
        data1: data1
      },
      success: function(result) {
        var memberList = $.parseJSON(result);
        for (var i = 0; i < memberList.length; i++) {
          console.log(memberList[i].fullName);
          document.getElementById("demo").innerHTML += '<li style="list-style:none;">' + memberList[i].fullName + '</li>';
        }
      }
    });
  }
  <div class="col-lg-3 mb-0" style="display: flex;align-items: center;">
    <div class="popup" onclick="myFunction()">
      <h6>My team</h6>
      <span class="popuptext" id="myPopup">My team members:<br><h7 id="demo"></h7><br></span>
    </div>
  </div>
</div>
<ol class="breadcrumb"></ol>

Upvotes: 0

Views: 283

Answers (1)

Vahid
Vahid

Reputation: 950

You need to clear demo element, before starting the for loop:

success: function(result) {
    var memberList = $.parseJSON(result);
    document.getElementById("demo").innerHTML = '';
    for (var i = 0; i < memberList.length; i++) {
          console.log(memberList[i].fullName);
          document.getElementById("demo").innerHTML += '<li style="list-style:none;">' + memberList[i].fullName + '</li>';
        }
    }

Personally, i prefer following code instead, when working with jquery:

$.ajax({
    url: 'TeamAssignment',
    type: 'POST',
    data: {
        data1: data1
    },
    dataType: "json",
    success: function(memberList) {
        $("#demo").html('');
        for (var i = 0; i < memberList.length; i++) {
            console.log(memberList[i].fullName);
            $("#demo").append('<li style="list-style:none;">' + memberList[i].fullName + '</li>');
        }
    }
});

Upvotes: 1

Related Questions