Quantcast
Channel: Active questions tagged javascript - Stack Overflow
Viewing all articles
Browse latest Browse all 141247

How to prevent user from adding more than 4 Tasks to a ToDo list in JavaScript

$
0
0

I have a todo list with very simple functionality. People can enter a new task in the input box and delete the task after it's added and also cross it out when its clicked in order to check the task off. I am trying to prevent the user from being able to add more than 4 tasks to the list. When the user enters a new value and there are already 4 tasks in the to do list there should be an alert that says they cannot exceed 4 tasks. This is my code, for some reason it doesn't work (it lets users add as many tasks as they want :

$("ul").on("click", "li", function() {
    $(this).toggleClass("completed");
});

var task= document.getElementById("task").childElementCount;

// remove to do

$("ul").on("click", "span", function(event) {
  $(this).parent().fadeOut(500, function() {
    $(this).remove();
  });  
    event.stopPropagation();
});



$("input[type='text']").keypress(function(event) {

    if(event.which === 13 && task <= 4) {

        //    grabbing new tasks from user
            var newTask = $(this).val();
            $(this).val("");
            // create a new li and add to ul
            $("ul").append("<li><span><i class='fa fa-trash'></i></span> " + newTask + "</li>")

    } else if (event.which === 13 && task > 4) {
        alert("you are trying to add too many tasks");
    }

}); ``` 

Viewing all articles
Browse latest Browse all 141247

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>