How to convert values in an input into an array of objects which get saved to local storage?

Viewed 180

I am new to HTML, JavaScript and Stack Overflow. I am currently making a website for creating and saving recipes.

I have an input (with an ID of "ingredient.value") for ingredients, and an "Add Ingredient" button which adds the ingredient from the input to the recipe.

For example, you could write "Pasta" in the ingredient input, and then press "Add Ingredient" which would add pasta into an unordered list. Then if you put another ingredient such as "Tomato Sauce" and pressed "Add Ingredient" again, it would put Tomato Sauce in the same unordered list, below "Pasta".

Then I have a "Save Recipe" button which I want to use to save the recipe into local storage.

So, my question is:

How would I go about making the "Add Ingredient" button turn the input into an array of objects, for example like this:

let fullRecipes = [{ ingredients: ["Pasta", "Tomato Sauce"] }];

and then make the "Save Recipe" button lock, and save the object into local storage, and then move onto a new object. So that once a recipe has been saved, the next recipe would be a new object like this:

let fullRecipes = [
  { ingredients: ["Pasta", "Tomato Sauce"] },
  { ingredients: ["newIngredient1", "newIngredient2"] }
];

Any pointers on how I could achieve this are greatly appreciated. Thanks.

1 Answers

I made a demo here

HTML:

<input id="ingredient.value">
<button id="addIngredient">Add ingredient</button>
<button id="save">Save</button>
<p id="ingredients"></p>
<p id="saved"></p>

JS:

var ingredients=[];
var recipe={};

document.getElementById("saved").innerText="Last saved: "+localStorage.getItem("ingredients");

document.getElementById("addIngredient").onclick=()=> {
    ingredients.push(document.getElementById("ingredient.value").value);
  document.getElementById("ingredients").innerText="Ingredients: "+ingredients;
}

document.getElementById("save").onclick=()=> {
    recipe["ingredients"]=ingredients;
    localStorage.setItem("ingredients", JSON.stringify(recipe));
  document.getElementById("saved").innerText="Saved: "+localStorage.getItem("ingredients");
}

Every time a user adds an ingredient, it adds that input value to an array. And when the user presses the save button, we save the array to localStorage as a string. (I saved it as a string because localStorage can only save strings.) To turn the saved ingredient in localStorage to a an array again, just do this JSON.parse(THE_THING_YOU_WANT_TO_TURN_BACK_INTO_AN_ARRAY)

Related