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
You can short circuit return in
createToDo
when the input don’t match specific constraints, e.g. when it is empty: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.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.
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.required
only works if you try to submit a<form>
without the field being filled.html
JS
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 thecreateToDo
when thesubmit
event triggers on the parent form.For the sake of records, a button is by default
type="submit"
.. here I just stressed out explictely