Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

How can I prevent the "Add" button from creating a task without an input value?

If the input field in the ADD ITEM section is empty, How can I stop the "Add" button from creating the task? Thanks in advance.

Hi Roberto,

Could you please post the code you have so we can see what you currently have.

https://teamtreehouse.com/forum/posting-code-to-the-forum

5 Answers

Thanks Herkko,

I forgot to provide some background for my question. This is related to this course: "Interactive Web Pages with JavaScript" http://teamtreehouse.com/library/interactive-web-pages-with-javascript

Specifically, the third section "Traversing and Manipulating the DOM with JavaScript".

The To-Do app we have to build as part of the course is already done. But the final video encourage the students to improve the app with a couple of issues to resolve.

This is the complete Javascript code:

//Problem: User interaction doesn't provide desired results.
//Solution: Add interactivity so the user can manage daily tasks.

//Add a new task
var taskInput = document.getElementById("new-task"); //new-task
var addButton = document.getElementsByTagName("button")[0]; //first-button
var incompleteTasksHolder = document.getElementById("incomplete-tasks"); //incomplete-tasks
var completedTasksHolder = document.getElementById("completed-tasks"); //completed-tasks

//New Task List Item
var createNewTaskElement = function (taskString) {
    //Create List Item
    var listItem = document.createElement("li");

        //input (checkbox)
        var checkBox = document.createElement("input"); //checkbox
        //label
        var label = document.createElement("label");
        //input (text)
        var editInput = document.createElement("input"); //text
        //button.edit
        var editButton = document.createElement("button");
        //button.delete
        var deleteButton = document.createElement("button");

    //Each elements needs modifying
    checkBox.type = "checkbox";
    editInput.type = "text";
    editButton.innerText = "Edit";
    editButton.className = "edit";
    deleteButton.innerText = "Delete";
    deleteButton.className = "delete";

    label.innerText = taskString;

    //Each element needs appending
    listItem.appendChild(checkBox);
    listItem.appendChild(label);
    listItem.appendChild(editInput);
    listItem.appendChild(editButton);
    listItem.appendChild(deleteButton);

    return listItem;
};

//Add a new task
var addTask = function () {
    console.log("Add task...");
    //Create a new list item with the text from #new-task:
    var listItem = createNewTaskElement(taskInput.value);
    //Append listItem to incompleteTasksHolder
    incompleteTasksHolder.appendChild(listItem);
    bindTaskEvents(listItem, taskCompleted);

    taskInput.value = "";   
    };

//Edit an existing task
var editTask = function () {
    console.log("Edit task...");

    var listItem = this.parentNode;
    var editInput = listItem.querySelector("input[type=text]");
    var label = listItem.querySelector("label");
    var editButton = listItem.getElementsByTagName('button')[0];

    var containsCLass = listItem.classList.contains("editMode");
        //if the class of the parent is .editMode
        if (containsCLass) {
            //Switch from .editMode
            //label text become the input's value
            label.innerText = editInput.value;
            editButton.innerText = "Edit";
        } else {
            //Switch to .editMode
            //input value becomes the label's text
            editInput.value = label.innerText;
            editButton.innerText = "Save";
        }

        //Toggle .editMode on the parent
        listItem.classList.toggle("editMode");
    };

//Delete an existing task
var deleteTask = function () {
    console.log("Delete task...");
    var listItem = this.parentNode;
    var ul = listItem.parentNode;

    //Remove the parent list item from the ul
    ul.removeChild(listItem);
};

//Mark a task as complete
var taskCompleted = function () {
    console.log("Task complete...");
    //Append the task list item to the #completed-tasks 
    var listItem = this.parentNode;
    completedTasksHolder.appendChild(listItem);
    bindTaskEvents(listItem, taskIncomplete);
};

//Mark a task as incomplete
var taskIncomplete = function () {
    console.log("Task incomplete...");
    //Append the task list item to the #incompleted-tasks
    var listItem = this.parentNode;
    incompleteTasksHolder.appendChild(listItem);
    bindTaskEvents(listItem, taskCompleted);
};

var bindTaskEvents = function (taskListItem, checkBoxEventHandler) {
    console.log("Bind list item events");
    //select taskListItem's children
    var checkBox = taskListItem.querySelector("input[type=checkbox]");
    var editButton = taskListItem.querySelector("button.edit");
    var deleteButton = taskListItem.querySelector("button.delete");
        //bind editTask to edit button
        editButton.onclick = editTask;
        //bind deleteTask to delete button
        deleteButton.onclick = deleteTask;
        //bind checkBoxEventHandler to checkbox 
        checkBox.onchange = checkBoxEventHandler;   
};

var ajaxRequest = function() {
    console.log("AJAX request");
};

//Set the click handler to the addTask function
// addButton.onclick = addTask;
addButton.addEventListener("click", addTask);
addButton.addEventListener("click", ajaxRequest);

//Cycle over incompleteTasksHolder ul list items
for (var i = 0; i < incompleteTasksHolder.children.length; i++) {
    //bind events to list item's children (taskCompleted)
    bindTaskEvents(incompleteTasksHolder.children[i],taskCompleted);
}

//Cycle over completedTasksHolder ul list items
for (var i = 0; i < completedTasksHolder.children.length; i++) {
    //bind events to list item's children (taskIncomplete)
    bindTaskEvents(completedTasksHolder.children[i],taskIncomplete);
}

You might want to check if the input model === "" with an if clause and include a createTask() function inside the if-clause. That way the createTask function is triggered only if the input field is not empty.

Hello,

What I got so far is that I tried to create another function under the addTask function. Something like this:

var blockAdd = function () {
    console.log("The input field is empty")
    if (taskInput.value === 0) {
             //blocking method
    } else {
               addButton.onclick = addTask;
        }
};

But, watching what Herkko is suggesting it seems I'm a little bit lost.

Thanks for your answers.

I have no idea if this is related to a treehouse challenge, but with the given information I would try this:

var checkTask = function () {
    if (taskInput.value != "") {
               addTask(taskinput.value);
        }
};

var addTask = function (taskName){
//code for adding the task
};

I dont know if the original value is null, or "". Try it out. But this code checks if the value is not "" and then runs the addTask function using the taskinput.value.

You just need to add the checkTask to the ADD button.

Hi Roberto Chaves ,

This is the code that gets executed when the "Add" button is clicked:

//Add a new task
var addTask = function () {
    console.log("Add task...");
    //Create a new list item with the text from #new-task:
    var listItem = createNewTaskElement(taskInput.value);
    //Append listItem to incompleteTasksHolder
    incompleteTasksHolder.appendChild(listItem);
    bindTaskEvents(listItem, taskCompleted);

    taskInput.value = "";   
    };

I think the easiest way (not the best way) to solve this problem is to wrap that code in the function inside an if block and don't execute that code unless the input has something in it.

var addTask = function() {
  if (taskInput.value !== "") {
    console.log("Add task...");
    //Create a new list item with the text from #new-task:
    var listItem = createNewTaskElement(taskInput.value);
    //Append listItem to incompleteTasksHolder
    incompleteTasksHolder.appendChild(listItem);
    bindTaskEvents(listItem, taskCompleted);

    taskInput.value = "";
  }
}

If the input is empty when you click then the if condition will be false and you won't execute any of that code.

The ajax request code also runs when you click the button:

var ajaxRequest = function() {
    console.log("AJAX request");
};

I don't know what this one is supposed to do but you probably would want to do the same thing for that one.

A better solution would probably be to disable the "add" button and only enable it if the input has something in it. Then you don't have to worry about putting in these if blocks because the click events won't go off.

You can disable the button near the top to start off with because the input is initially empty.

var addButton = document.getElementsByTagName("button")[0]; //first button
addButton.disabled = true;

Then you can respond to the "input" event on the task input to continually monitor whether the button should be enabled or disabled.

//Set the click handler to the addTask function
addButton.addEventListener("click", addTask);
addButton.addEventListener("click", ajaxRequest);

// This will continually monitor the task input box for changes and disable/enable the add button
taskInput.addEventListener("input", function() {
  if (this.value === "") {
    addButton.disabled = true;
  }
  else {
    addButton.disabled = false;
  } 
});

Then you would probably want to put something in the css to indicate to the user that the button is disabled.

This is what I did:

p > button:hover {
  color: #0FC57C;
}

/* I added the following around line 79 in the css file */
p > button:disabled {
  color: red;
  cursor: default;
  opacity: .25;
}