shinryu333 shinryu333 - 15 days ago 5
HTML Question

Javascript: Creating a Shopping List Using Web Storage

I have the following exercise question that I'm having a hard time wrapping my head around:

enter image description here

So far I've started the code off as such:



<!DOCTYPE html>
<html>
<head>
<title></title>
<script>
function addItem(){
var form = document.getElementById("form1");
var item = form.elements["name"].value;
var cost = form.elements["price"].value;

//what should I do next?
}

function removeItem(){
//remove item code here
}
</script>
</head>
<body>
<form id="form1">
Item Name: <input name="name" type="text">
Item Cost: <input name="price" type="text">
<button onclick="addItem()">Add</button>
<button onclick="removeItem()">Remove</button>
</form>
<div id="div1">
<ul id="ul1">
</ul>
</div>
</body>
</html>





I have the basic structure of how I want my page to look. I know that I will have to create two functions that will handle the add item and remove item criteria in the question. However, I'm sort of lost at the point where I have to save the user's input. I know that I have to use web storage and possibly an array? How should this be coded?

Would appreciate any insight. Thanks in advance.

Answer
var testObject = { 'one': 1, 'two': 2, 'three': 3 };

// Put the object into storage
localStorage.setItem('testObject', JSON.stringify(testObject));

// Retrieve the object from storage
var retrievedObject = localStorage.getItem('testObject');

console.log('retrievedObject: ', JSON.parse(retrievedObject));

Source: Storing Objects in HTML5 localStorage