skip to Main Content

I am making a ‘TO DO’ list which takes a task that has been inputted by the user and displays it in a list.

I am trying to set the input for the task to be ‘required’ so that the user can’t submit an ‘Empty’ task.

HTML:

<div>
    <input type="text" id="task" placeholder="What do you need to do?" />
    <button class="btn" onclick="createToDo()">Submit</button>
    <button class="btn" onclick="window.location.reload()">
        Clear List
    </button>
</div>

JS:

function createToDo() {
    var input = document.getElementById("task").value;
    var ul = document.getElementById("list");
    var li = document.createElement("li");
    var remove = document.createElement("button");
  
    remove.classList.add("remove");
    remove.innerHTML = "Complete";
    remove.addEventListener("click", ({ target }) =>
        target.parentElement.remove()
    );
  
    li.appendChild(document.createTextNode(input));
    ul.appendChild(li);
    li.appendChild(remove);
}

I have tried to add it directly to the HTML but it doesn’t work:

<input type="text" id="task" placeholder="What do you need to do?" required/>

I have also tried to inject it through JS, but this doesn’t seem to work either:

const taskInput = document.getElementById("task");
taskInput.setAttribute("required");

I understand that when I click the submit it runs the function to create the list, so I’m not sure if there is something that I have to change within the function.

Any help is greatly appreciated.

5

Answers


  1. You can short circuit return in createToDo when the input don’t match specific constraints, e.g. when it is empty:

    var input = document.getElementById("task").value;
    if (!input) return;
    

    A potential alternative is to wrap all the controls in a <form> element to let the browser check, but I am not sure about this.

    Login or Signup to reply.
  2. If you use a form and the submit event it will trigger the required.

    Here is a full version using event listeners and delegation

    I removed the reload and clear the list instead.

    window.addEventListener("DOMContentLoaded", () => {
      const input = document.getElementById("task");
      const list = document.getElementById("list");
      const form = document.getElementById("todoForm");
      const clear = document.getElementById("clear");
      form.addEventListener("submit", (e) => {
        e.preventDefault(); // stop submission;
        let task = input.value.trim();
        if (task === "") return;
        let li = document.createElement("li");
        var remove = document.createElement("button");
        remove.classList.add("remove");
        remove.innerHTML = "Complete";
        li.appendChild(document.createTextNode(task));
        li.appendChild(remove);
        list.appendChild(li);
        input.value = "";
      });
      clear.addEventListener("click",() => list.innerHTML = "");
      list.addEventListener("click", ({ target }) => 
        target.matches(".remove") && target.closest("li").remove()
      );
    
    })
    <form id="todoForm">
      <div>
        <input type="text" id="task" placeholder="What do you need to do?" required/>
        <button type="submit" class="btn">Submit</button>
        <button type="button" class="btn" id="clear">
            Clear List
        </button>
      </div>
    </form>
    <ul id="list"></ul>
    Login or Signup to reply.
  3. The required attribute in HTML is used for form validation, and it works when the input is inside a <form> element and you are trying to submit that form.

    OR

    You can add a validation check within the createToDo() function.

    function createToDo() {
        var input = document.getElementById("task").value.trim();
        if (input !== "") {
            var ul = document.getElementById("list");
            var li = document.createElement("li");
            var remove = document.createElement("button");
    
            remove.classList.add("remove");
            remove.innerHTML = "Complete";
            remove.addEventListener("click", ({ target }) =>
                target.parentElement.remove()
            );
    
            li.appendChild(document.createTextNode(input));
            ul.appendChild(li);
            li.appendChild(remove);
            document.getElementById("task").value = ""; 
        } else {
            alert("Please enter a task!");
        }
    }
    
    Login or Signup to reply.
  4. required only works if you try to submit a <form> without the field being filled.

    html

    <div>
        <form id="myform">
        
        <input type="text" id="task" required placeholder="What do you need to do?" />
        <button type="submit" class="btn">Submit</button>
         <button class="btn" onclick="window.location.reload()">
            Clear List
        </button>
        </form>
        
    </div>
    

    JS

    document.querySelector("#myform").addEventListener("submit", (e) => submitForm(e))
    
    function submitForm(e) {
        e.preventDefault()
        // your todolist code here
    }
    
    Login or Signup to reply.
  5. If you wished to use the standard Client-side form validation, you need to use a <form> element and rely on its submit event instead of binding the handler to the click event of a <button type="button">.

    Here in this demo I used the required attribute for <input> and called the createToDo when the submit event triggers on the parent form.

    For the sake of records, a button is by default type="submit" .. here I just stressed out explictely

    function createToDo() {
      var input = document.getElementById("task").value;
      var ul = document.getElementById("list");
      var li = document.createElement("li");
      var remove = document.createElement("button");
    
      remove.classList.add("remove");
      remove.innerHTML = "Complete";
      remove.addEventListener("click", (event) => {
        event.target.parentElement.remove()
      });
    
      li.appendChild(document.createTextNode(input));
      ul.appendChild(li);
      li.appendChild(remove);
    }
    <form onsubmit="event.preventDefault();createToDo();">
      <div>
        <input type="text" id="task" placeholder="What do you need to do?" required />
        <button type="submit" class="btn">Submit</button>
        <button class="btn" onclick="window.location.reload()">Clear List</button>
      </div>
    </form>
    
    <ul id="list">
    </ul>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search