Js
var button = document.getElementById("enter");
var input = document.getElementById("userinput");
var ul = document.querySelector("ul");
function inputLength() {
return input.value.length;
}
function createListElement() {
var li = document.createElement("li");
li.appendChild(document.createTextNode(input.value));
ul.appendChild(li);
input.value = "";
}
button.addEventListener("click", function () {
if (inputLength > 0) {
createListElement();
}
})
input.addEventListener("keydown", function () {
if (inputLength > 0 && event.key === "Enter") {
createListElement();
}
})
Html
<!DOCTYPE html>
<html>
<head>
<title>Javascript + DOM</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<h1>Shopping List</h1>
<p id="first">Get it done today</p>
<input id="userinput" type="text" placeholder="enter items">
<button id="enter">Enter</button>
<ul>
<li class="bold red" random="23">Notebook</li>
<li>Jello</li>
<li>Spinach</li>
<li>Rice</li>
<li>Birthday Cake</li>
<li>Candles</li>
</ul>
<script type="text/javascript" src="script.js"></script>
</body>
</html>
Before I didn’t have any of the both functions(inputLength, createListElement) and things went well, but after I simplified the code the input function stopped working.
Everything seems to be ok, checked it for several times and the console doesn’t show me any error.
>Solution :
You are not calling the inputLength function.
You are not getting any error because inputLength > 0 is still a valid expression, it just doesn’t get evaluated as true.
To fix your problem, call the function like:
button.addEventListener("click", function () {
if (inputLength() > 0) {
createListElement();
}
});
input.addEventListener("keydown", function () {
if (inputLength() > 0 && event.key === "Enter") {
createListElement();
}
});