Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why does the input doesn't work after I reduced the size of the code by adding 2 functions?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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();
    }
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading