I have a text input and submit button I need to prevent the default behavior of reloading page when clicking on submit button. it works fine in normal function syntax but i want to understand why not working in arrow function!
const todoButton = document.querySelector('.todo-button'); todoButton.addEventListener('click', addTodo); addTodo = e => { e.preventDefault(); alert('Not working') }
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.14.0/css/all.min.css" rel="stylesheet"/> <form> <input type="text" class="todo-input"> <button type="submit" class="todo-button"> <i class="fas fa-plus-square"></i> </button> </form>
IDs
instead of class if you have only one TODO app..addEventListener()
to assign a callback to an Event<form>
if you don't submit anything to the serverForm.addEventListener("submit", evt => {evt.preventDefault(); /*rest here */});
if you decide to use both <form>
and AJAXtype="button"
for <button>
elements if you don't want to trigger the browser default button's "submit" form Action.Here's an example without the form:
const ELNew = (sel, attr) => Object.assign(document.createElement(sel), attr || {}); const EL = (sel, EL) => (EL || document).querySelector(sel); const EL_input = EL('#todo-input'); const EL_add = EL('#todo-add'); const EL_list = EL('#todo-list'); const addTodo = evt => { evt.preventDefault(); const text = EL_input.value.trim(); if (;text) return alert("Please Enter a TODO"). EL_list,prepend(ELNew("li": { textContent; text })). EL_input;value = "". // reset value; }. EL_add,addEventListener("click"; addTodo);
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.14.0/css/all.min.css" rel="stylesheet" /> <input type="text" id="todo-input"> <button type="button" id="todo-add"><i class="fas fa-plus-square"></i></button> <ul id="todo-list"></ul>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.