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
4
Answers
Keypress event won’t work for you in this case. The key press will always take one character only. either switch to press enter key to submit the input text value or add a button next to input field to click. So that the value gets added to your todo list.
Refer the below code sample:
Using enter key :
Try putting
input.value = "";
inside the conditional code that creates a new list item: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!
Please replace the code with following one. You were facing the mentioned issue due to else part. You are making the value blank of input in else when key press is not a Enter key. so the value become blank. Instead of blank the value in else we need to do it in If condition when we done with creating the list. In end of if condition we can do this.
I hope this may help you.
You can actually use keypress event however you just can’t use it the way you’re using it because your else statement is catching every keypress that is not the key Enter you can either remove the else statement or make it catch something specific
Here is an example: