0

I am currently working on a to-do list application using HTML, CSS, and JavaScript. I have a text input field where users can enter their tasks, and a "Add Task" button to add the task to the list. However, I would like to improve the user experience by allowing them to add tasks simply by pressing the Enter key on their keyboard.

How can I implement this functionality in my application? Are there any specific event listeners or key codes that I should use to detect the Enter key press and trigger the task addition function? Additionally, how can I ensure that the input field is cleared after adding a task?

I would greatly appreciate any guidance, code snippets, or recommended approaches to accomplish this feature. Thank you in advance for your help!

I can only add them by clicking on the button

1 Answers1

1

To allow users to add tasks by pressing the Enter key, you can add an event listener to the input field that listens for the "keydown" event. When the Enter key is pressed, you can call the function that adds the task to the list.

This below code will give you an idea on how to achieve your task

<input type="text" id="taskInput">
<button id="addTaskBtn">Add Task</button>

<script>
  const taskInput = document.getElementById("taskInput");
  const addTaskBtn = document.getElementById("addTaskBtn");

  taskInput.addEventListener("keydown", function(event) {
    if (event.key === "Enter") {
      addTask();
    }
  });

  addTaskBtn.addEventListener("click", function() {
    addTask();
  });

  function addTask() {
    const task = taskInput.value;
    if (task.trim() !== "") {
      // Add task to the list
      console.log("Task added:", task);
      taskInput.value = "";
    }
  }
</script>

const taskInput = document.getElementById("taskInput");
const addTaskBtn = document.getElementById("addTaskBtn");

taskInput.addEventListener("keydown", function(event) {
  if (event.key === "Enter") {
    addTask();
  }
});

addTaskBtn.addEventListener("click", function() {
  addTask();
});

function addTask() {
  const task = taskInput.value;
  if (task.trim() !== "") {
    // Add task to the list
    console.log("Task added:", task);
    taskInput.value = "";
  }
}
<input type="text" id="taskInput">
<button id="addTaskBtn">Add Task</button>
cssyphus
  • 37,875
  • 18
  • 96
  • 111
  • Good answer Sumuditha - When answering a question, you can press `Ctrl` + `M` to open a jsFiddle-like interface and create a "Stack Snippet" to turn your code into a working interactive demo – cssyphus May 30 '23 at 11:41
  • Got it! Thanks for the tip sir. That was my first answer in stack :D – Sumuditha Lansakara May 30 '23 at 11:45