Home > Software engineering >  How to avoid values from an object after inserting from an input form to be inserted repeatedly?
How to avoid values from an object after inserting from an input form to be inserted repeatedly?

Time:08-28

I am inserting the values of an input into an array of objects. Then, I want to get those values e show inside the HTML. Inserting each value inside the object is not the problem, every time I click the button, each value is successfully added. When I console.log() the array, it shows only one of each value added. The problem is when I try to show the content of the object inside the HTML element, it inserts all the data from the object over and over again, but I just want to add the last value added and keep what was previously inserted, not to add everything again.

What am I doing wrong?

This is my HTML

    <main>
      <div >
        <form id="form">
          <h2>Add Recipe</h2>
          <div >
            <div >
              <label for="title"
                >Title
                <input type="text" name="title" id="recipe-title" />
              </label>
            </div>
          </div>
          <button id="send-recipe-btn" type="submit">Send Recipe</button>
        </form>
      </div>
      <div ></div>
    </main>

This is my JS File

let recipes = [];
const addRecipe = e => {
    e.preventDefault();
    let recipe = {
        title: document.getElementById('recipe-title').value
    };
    recipes.push(recipe);
    document.querySelector('form').reset();
    recipes.forEach(e => {
        const recipeContainer = document.querySelector('.recipes-container');
        const recipeTitle = document.createElement('div');
        recipeTitle.classList.add('recipe-title');
        recipeContainer.append(recipeTitle);
        recipeTitle.textContent = e.title;
    });
    console.log(recipes);
};

document.getElementById('send-recipe-btn').addEventListener('click', addRecipe);

Thanks for any tip or help to solve this.

CodePudding user response:

Have the forEach()loop to start before recipeTitle.textContent = e.title;

let recipes = [];
const addRecipe = e => {
    e.preventDefault();
    let recipe = {
        title: document.getElementById('recipe-title').value
    };
    recipes.push(recipe);
    document.querySelector('form').reset();
        const recipeContainer = document.querySelector('.recipes-container');
        const recipeTitle = document.createElement('div');
        recipeTitle.classList.add('recipe-title');
        recipeContainer.append(recipeTitle);
    recipes.forEach(e => {
        recipeTitle.textContent = e.title;
    });
    console.log(recipes);
};

document.getElementById('send-recipe-btn').addEventListener('click', addRecipe);

CodePudding user response:

In your event handler, you are looping over the recipes array and creating a new element every single time the button is pressed.

Just remove the loop and it will work properly

  • Related