Alexander Alexander - 6 months ago 10
Javascript Question

Issue with displaying a JavaScript array into an HTML div

When I try to loop through my array, the result is the entire array being displayed each time the button is clicked (doubling up). Instead I would like to have the array being displayed with the new item appended only.

Thanks :^)

<!DOCTYPE HTML>
<html>
<head>
<title>Checklist</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script>
$(function() {
var arr = [];
$("button").click(function() {
arr.push($(":text").val());
$(":text").val("");
for(i in arr){
$("#x").append(arr[i] + "<br>");
}
//x.text(JSON.stringify(arr));
})
})
</script>
</head>
<body>

<input type="text" id="item" placeholder="Enter an item">
<button id="add">Add Item</button>
<br>
<div id="x"></div>
</body>
</html>

Answer

Why don't you get the last element of the Array, and then append it, instead of using this for...in loop:

<!DOCTYPE HTML>
<html>
<head>
    <title>Checklist</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
  <script>
    $(function() {
      var arr = [];
       $("button").click(function() {
         arr.push($(":text").val());
         $(":text").val("");
         $("#x").append(arr[arr.length - 1] + "<br>");
       })
     })
    </script>
</head>
<body>  

    <input type="text" id="item" placeholder="Enter an item">
    <button id="add">Add Item</button>
    <br>
    <div id="x"></div>
</body>
</html>

See it in action: http://codepen.io/gabrielgodoy/pen/oLNrxj

Comments