Search code examples
javascriptformsfor-loopuser-inputgetelementbyid

Why does a previous name I inputed repeat itself each time I input a new name on a form and click on add?


JavaScript: My form input value keeps repeating itself. Each time I enter a new name in the input field and click on the add button, the previous name I entered repeats itself and the new name is also added to the name list. Hence, if I input two names, I end up getting three with the first one repeating itself before the new one. Find attached my code:

let inputvalue = document.querySelector("#womansname");
let addbtn = document.querySelector("#submit");
let displayname = document.querySelector(".taskList");

let nameList=[]
let list= ""
let li=document.createElement("li");

addbtn.addEventListener("click", (e)=> {
      e.preventDefault();
     nameList.push( inputvalue.value)
     for (let index = 0; index < nameList.length; index++) {
      list += `<li>${nameList[index]}</li>`
}

      displayname.innerHTML=list;
      inputvalue.value=""

})

Solution

  • your problem is that you don't reset your list every time you press your button. so you keep adding the previous data to the list. The simple solution is to move the list instantiation into the click-eventListener, then your list will only add the new data.

    let inputvalue = document.querySelector("#womansname");
    let addbtn = document.querySelector("#submit");
    let displayname = document.querySelector(".taskList");
    
    let nameList = []
    let li = document.createElement("li");
    
    addbtn.addEventListener("click", (e) => {
      e.preventDefault();
      nameList.push(inputvalue.value);
      let list = "";
      for (let index = 0; index < nameList.length; index++) {
        list += `<li>${nameList[index]}</li>`
      }
    
      displayname.innerHTML = list;
      inputvalue.value = "";
    })
    <div>
      <input id="womansname" />
      <button id="submit">
      submit
      </button>
      <ul class="taskList">
    
      </ul>
    </div>