I am trying to create a list type todo App. The code works fine up to a point. when I click on my submit button the list item is created and it can be briefly seen on the page after which it disappears. Here is my HTML
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="style.css">
<script src="/script.js" defer></script>
</head>
<body>
<h1>My shopping list</h1>
<form class="form-control">
<div>
<label for="text">Enter a new item</label>
<input type="text" name="text" id="123" >
</div>
<div>
<button>Submit</button>
</div>
</form>
<ul id="11"></ul>
</body>
</html>
and here is the javacript file
const input = document.querySelector('input')
const list = document.querySelector('ul')
const button = document.querySelector('button')
button.addEventListener('click',()=>{
const myData = input.value
input.value = ''
const newdiv = document.createElement('div')
newdiv.classList.add('newdiv');
const listInput = document.createElement('li')
const textdata = document.createElement('span')
textdata.textContent = myData;
const delButton = document.createElement('button')
delButton.textContent = 'delete';
listInput.appendChild(textdata)
newdiv.appendChild(listInput)
newdiv.appendChild(delButton)
list.appendChild(newdiv)
delButton.addEventListener('click',()=>{
list.removeChild(listInput)
})
})
hopefully someone can tell me what I am doing wrong
3
Answers
I just removed the
<form></form>
tag and it works as expectedPlease see preventDefault and keep the
form
tags.https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault
Without form your code works because form is not send on button click.
as @Jack said, add event.preventDefault() to button click event to prevent form submit.
See code below