Sorry in advance if I'm not making any sense. I'm a complete beginner to coding. I'm creating a shopping list and a user will enter the items through placeholder and will click or press enter to add the items in the list.
The click event is working properly.
Edit
var button = document.getElementById("enter");
var input = document.getElementById("userinput");
var ul = document.querySelector("ul");
button.addEventListener("click", function() {
if (input.value.length > 0) {
var li = document.createElement("li");
li.appendChild(document.createTextNode(input.value));
ul.appendChild(li);
input.value = "";
}
})
document.addEventListener('keydown', 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 = "";
}
});
<input type='text' id='userinput' />
<button type='button' id='enter'>Enter</button>
<ul></ul>
Can you elaborate more on your question? Also, stick to the "DRY" principle. You have both the button and the input adding a item then adding it to the list: Make a function that takes the input and call it on both the button and the input event:
function addListItem(input){
var li = document.createElement("li");
li.appendChild(document.createTextNode(input.value));
ul.appendChild(li);
input.value = "";
};
It'll look like this:
button.addEventListener("click", function() {
if (input.value.length > 0) {
AddListItem(input);
}
});
input.addEventListener('keyup', function (event) {
if (input.value.length > 0 && event.key === 'Enter') {
AddListItem(input);
}
});
// So, If I'm getting it correct. You have an input field and you're //reading values from that field // So add 'keyup' to input element. // Fix the IF // control the input length in order to control values?
I need more info on this: How to prevent entering more value when I press enter using keydown event
var input = document.getElementById("userinput");
var ul = document.querySelector("ul");
var btn = document.querySelector('#enter')
btn.addEventListener("click", function() {
if (input.value.length > 0) {
var li = document.createElement("li");
li.appendChild(document.createTextNode(input.value));
ul.appendChild(li);
input.value = "";
}
})
input.addEventListener('keyup', function (event) {
//basically, if the input value is falsy('') you return nothing or false (abort)
if(!input.value) {
return;
//return false;
//alert('cannot add empty list item')
}
if (input.value.length > 0 && event.key === 'Enter') {
var li = document.createElement("li");
li.appendChild(document.createTextNode(input.value));
ul.appendChild(li);
input.value = "";
}
});