Search code examples
javascriptdomeventsevent-handling

Stop loading onload content when button is clicked


I have an HTML file with this body:

<body onload="loadContent()">
  <form action="" onsubmit="event.preventDefault()">
    <table>
      <tr>
        <td></td>
        <td> 
          <button type="submit" onclick="saveNewProject()">Save</button>
        </td>
      </tr>
    </table>
  </form>
</body>

It includes a form and there's a button to save new content:

<button type="submit" onclick="saveNewContent()">Save</button>

When the page is loaded, an array with existing content is loaded and then when adding new content by filling the form and clicking "save", the page should display the existing content AND the new content.

I already managed to display the new content. The issue I have is that anytime I click SAVE, the page now shows me the existing content TWICE plus the newly entered content.

For example: there are 3 existing elements, I add a 4th one and click save and now I see the 3 existing elements repeated and the newly entered element (a total of 7 elements instead of 4).

The saveNewContent function IS SUPPOSED to include the loadContent function:

function saveNewContent() {
  loadContent();
}

How can I stop repeating the existing content everytime I add new content? I just want to be able to see the existing content once plus the newly added content.

This is the loadContent() function. It goes through an array of objects and the saveNewContent creates and adds new objects into that same array of objects.

function loadContent() {
  for (var i=0; i < contents.length; i++) {
    card                    = document.createElement('div')
    card.className          = 'card'
    description             = document.createElement('span')
    description.textContent = contents[i]["description"]
    contentCard             = document.getElementById("contents").appendChild(card)
    contentCard.appendChild(description)
  }

Solution

  • It looks like every time loadContent() is called everything is added again. Maybe it solves your problem if you clear everything before you add it again:

    function loadContent () {
      // clear everything at first:
      document.getElementById("contents").innerHTML = ""
      for ( /* ... */ ) {
        // ...
      }
    }