0

I'm trying to output an array of items to a list. The problems is when I click submit it's adding all the array items to each list item instead of one each time.

JSFIDDLE: https://jsfiddle.net/b7Lwbrof/

Thanks!

var itemList = [];
var container = document.getElementById('container');

// On click
document.getElementById('submit').addEventListener("click", function(){
    var itemValue = document.getElementById('itemValue').value;

    // Push to array
    itemList.push(itemValue);

    // Append to List
    for(i=0; i<itemList.length; i++) {
        var items = document.createElement("li");
        document.getElementById('container').appendChild(items);
        items.innerHTML = itemList[i];
    }
})
2
  • you could either append the last item to the list, or rewrite the whole list. Commented Feb 12, 2017 at 10:53
  • @NinaScholz: his logic aims to rewrite the whole list. . Commented Feb 12, 2017 at 10:57

2 Answers 2

2

You don't need loop then, just append the item after it has been push to the itemList.

document.getElementById('submit').addEventListener("click", function(){
    var itemValue = document.getElementById('itemValue').value;

    // Push to array
    itemList.push(itemValue);

    // Append to List
     var items = document.createElement("li");
     document.getElementById('container').appendChild(items);
     items.innerHTML = itemList[itemList.length-1];
})
Sign up to request clarification or add additional context in comments.

Comments

2
items.innerHTML = itemList[itemList.length - 1] // get the last

and NOT

items.innerHTML = itemList[i]

And remove the loop as @digit said .

Fiddle here

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.