Guy Shifty
Guy Shifty

Reputation: 33

Form button keeps reloading page

This is in a form: <button class="addrecipe-button" type="submit" name="recipe-submit"></button>

Immediatley after I have this within a script tag:

const addRecipeButton = document.querySelector(".addrecipe-button");
                                    addRecipeButton.addEventListener("submit",addRecipe);

                              var recipeEntry = [];

                              const addRecipe = function(event){
                                  event.preventDefault();
                                  let recipe = {
                                      type :document.querySelector(".recipe-type").value,
                                      title :document.querySelector(".recipe-title").value,
                                      description :document.querySelector(".recipe-description").value,
                                      instructions :document.querySelector(".recipe-instructions").value,
                                      photo :document.querySelector(".recipe-photo").value,
                                      meats :document.querySelector(".recipe-meats").value,
                                      dairy :document.querySelector(".recipe-dairy").value,
                                      spices :document.querySelector(".recipe-spices").value,
                                      fruitveg :document.querySelector(".recipe-fruitveg").value,
                                      preptime :document.querySelector(".recipe-preptime").value,
                                      cooktime :document.querySelector(".recipe-cooktime").value,
                                      totaltime :document.querySelector(".recipe-totaltime").value
                                  }
                                  recipeEntry.push(recipe);

                              }
                              
                              console.log(recipeEntry);

I can't understand why "event.preventDefault()" is not stopping the page from reloading. Also, the "recipeEntry" variable is staying empty when console.logged. Can someone please review my code?

Upvotes: 1

Views: 39

Answers (1)

Vincent Ramdhanie
Vincent Ramdhanie

Reputation: 103135

Since the addRecipe button is on a form you need to target the form rather than the button. The button does not have a submit event. Change the selector to your form, maybe like this:

const addRecipeForm = document.querySelector("YOUR_FORM_SELECTOR");
                                
addRecipeForm.addEventListener("submit",addRecipe);

Upvotes: 1

Related Questions