Computer >> Computer tutorials >  >> Programming >> Javascript

Create a to-do list with JavaScript


Example

Following is the code to create a to-do list −

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <title>Document</title>
</head>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<body>
   <input type="text" placeholder="Please Enter your Task Here.." id="txtData">
   <button onclick="todoList()">AddTaskToDo</button>
   <ul id="to_do_list">
   </ul>
</body>
<script>
   function todoList() {
      const myTask = document.getElementById('txtData');
      const addToDoList = document.getElementById('to_do_list');
      let originalValue = `<li> ${myTask.value} </li>`;
      myTask.value = '';
      addToDoList.insertAdjacentHTML('beforeend', originalValue);
   }
</script>
</html>

To run the above program, save the file name “anyName.html(index.html)”. Right click on the file and select the option “Open with Live Server” in VSCode editor −

This will produce the following output −

Create a to-do list with JavaScript

Now here, I am going to enter first task.

Create a to-do list with JavaScript

After entering the first task, click the button.

Output

This will produce the following output on console −

Create a to-do list with JavaScript

Again, I am entering one more task.

Create a to-do list with JavaScript

After clicking the button, you will get the following output −

Create a to-do list with JavaScript