i wanted to add a userinput in a todo list using keypress but only one character is taken by the input filed.
this is the code:
input.addEventListener("keypress", function(event){
if(input.value.length>0 && event.key === 'Enter'){
var li = document.createElement("li");
li.appendChild(document.createTextNode(input.value));
ul.appendChild(li);
} else input.value = "";
i tried using keyup but using Keyup does not take any input rather it just show the input for an instance but then the input filed deletes it automatically
Try putting input.value = "";
inside the conditional code that creates a new list item:
const input = document.querySelector("input");
const ul = document.querySelector("ul");
input.addEventListener("keypress", function(event){
if(input.value.length>0 && event.key === 'Enter'){
var li = document.createElement("li");
li.appendChild(document.createTextNode(input.value));
ul.appendChild(li);
input.value = ""; // it's now in the li.
}
});
Type in to do text and press Enter: <input type="text">
<p>
<ul></ul>
At the moment clearing the input element's content is in the wrong spot - the code needs to allow the user to enter to do information without erasing it!