2

Javascript newbie here. I made an javascript application that adds and removes item elements from a list array. The add functions. The delete doesn't function. I think maybe the item elements are being deleted from the array, however; the array isn't being "refreshed" on the webpage. Anybody know how to make it work? Thanks, Eliza

HTML:

<p>GROCERY LIST-INATOR</p>
<p>Click the button to add an item to grocery list.</p>

<button onclick="addItem()">Add item</button>
<button onclick="deleteItem()">Delete item</button>

<p id="list"></p>

JS:

var list = [];

function addItem (){
    var name = prompt("Enter item name:");
    list.push(name);
    var today = Date();
    var string = "Created on " + today + "<br>" + " My Grocery List: <br>";
    for (var key in list){
        string += "- " + list[key] + "<br>";
    }
    document.getElementById("list").innerHTML = string;
};

function deleteItem (){
    var item = prompt("Enter item name:");
    for(var i = list.length - 1; i >= 0; i--) {
        if(list[i] === item) {
        list.splice(i, 1);
    }
}
   document.getElementById("list").innerHTML = string;
};

http://jsfiddle.net/elizaway/9d0376t1/

elizaway
  • 21
  • 1
  • There is no `string` varialbe in second function. `string` variable created in first function is local and visible only to function scope. – Eugene Sep 26 '15 at 03:20
  • Working example http://jsfiddle.net/9d0376t1/1/ You may also want to look into http://stackoverflow.com/questions/500431/what-is-the-scope-of-variables-in-javascript. – Eugene Sep 26 '15 at 03:26

1 Answers1

-1

You are not updating string variable in your second function. Try add you string related code in second function before use string variable and you are done..

var string = "Created on " + today + "<br>" + " My Grocery List: <br>"; 
for (var key in list)
  { 
    string += "- " + list[key] + "<br>"; 
   }

Above code come between for loop and this code.

document.getElementById("list").innerHTML = string;
Dipak Gupta
  • 7,321
  • 1
  • 20
  • 32