jimmy118
jimmy118

Reputation: 323

input field accepting no value input despite if statement validation

html:

<header>
<h1>ENTER A TASK BELOW</h1>
<input type="text" id="task"><img id="add" src="add.png">

</header>


<div id="incomplete-tasks">
<h4>TO-DO LIST</h4>
<ul id="task-to-do">

</ul>
</div>

javascript / jquery:

$(document).ready(function() {
    document.getElementById("add").addEventListener("click", function() {
        var taskinput = document.getElementById("task").value;
        if (taskinput) {
            var tasktext = document.createTextNode(taskinput);
            var list = document.createElement("li");
            list.appendChild(tasktext);
            var button = document.createElement("button");
            button.setAttribute("class", "completed");
            button.innerHTML = "X";
            list.appendChild(button);
            var toDoList = document.getElementById("task-to-do");
            toDoList.insertBefore(list, toDoList.childNodes[0]);
            document.getElementById("task").value = " ";
        } else {
            alert("Please enter a task");
        }
    });
    $(document).on('click', "button.completed", function() {
        $(this).closest("li").remove();
    });
});

This is a simple to-do list I am working on. One of the things I have put in place is for an alert box to pop up if the user hits the "add" image/button without inputting anything into the field below "Enter a task".

However, something is wrong and it is allowing the user to add empty input values. I can not see what I am doing wrong here. Please can someone assit? Many thanks!

Upvotes: 0

Views: 19

Answers (1)

liontass
liontass

Reputation: 740

I made a small correction in your javascript/jquery code.In the if condition I added the trim() method to check if there is an empty characters string.

$(document).ready(function() {
    document.getElementById("add").addEventListener("click", function() {
        var taskinput = document.getElementById("task").value;

        if ($.trim(taskinput)!== '') {
            var tasktext = document.createTextNode(taskinput);
            var list = document.createElement("li");
            list.appendChild(tasktext);
            var button = document.createElement("button");
            button.setAttribute("class", "completed");
            button.innerHTML = "X";
            list.appendChild(button);
            var toDoList = document.getElementById("task-to-do");
            toDoList.insertBefore(list, toDoList.childNodes[0]);
            document.getElementById("task").value = " ";
        } else {
            alert("Please enter a task");
        }
    });
    $(document).on('click', "button.completed", function() {
        $(this).closest("li").remove();
    });
});

Upvotes: 1

Related Questions