The page keeps updating even using preventDefault() in javascript

Asked

Viewed 65 times

0

Hello, I’m trying to develop a list to, I confess I’m getting a little hahaha. I’m following a gringo tutorial and stopped at a very boring part.
I added a form, put an input to write the task, and on the button I put an Alert with the Eventlistener just to see if it was working, and every time I press the button, the page reloads. I’ve tried preventDefault() and Stoppropagation and nothing, anyone could enlighten me?
Don’t mind the crappy CSS, I’m really getting hahahahha.

<header>
<h1>
    Vitor's to do
</h1>
<form>
    <input type="text" class="todo-input">
    <button class="todo-button" type="submit">
        <!-- o type originalmente é submit, mas vou mudar para button apra
          parar de dar refresh na pagina, se der algum problema la na frente
          é isso que eu mudei!!!!!!!!!!!-->
        <i class="fas fa-plus-square"> </i>
    </button>
</form>
    <div class="todo-container">
        <ul class="todo-list">  
        </ul>
    </div>
</header>

/SELECTORS
const todoInput = document.querySelector('.todo-input')
const todoButton = document.querySelector('.todo-button').addEventListener('submit', addTodo)
const todoList = document.querySelector('.todo-list')
//Evente Listeners
//todoButton.addEventListener('submit', addTodo)
//Functions
function addTodo(event){
    event.preventDefault();
    window.alert('testing')
}

1 answer

0


The event is in the wrong place, the event submit is from the form (</form>), then, look for the form that in the example case I put a class todo-form (<form class="todo-form">), to add the event:

const todoInput = document.querySelector('.todo-input')
const todoButton = document.querySelector('.todo-button')
const todoForm = document.querySelector('.todo-form');
todoForm.addEventListener('submit', addTodo)
const todoList = document.querySelector('.todo-list')
function addTodo(event) {  
  event.preventDefault();
  window.alert('testing')
}
<form class="todo-form">
  <input type="text" class="todo-input">
  <button class="todo-button" type="submit">      
        Enviar
    </button>
</form>
<div class="todo-container">
  <ul class="todo-list">
  </ul>
</div>

  • Thanks man, you helped me a lot!!!!!!!!!!

  • @Vitorg ticks in response to your post!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.