Untitled
unknown
plain_text
5 days ago
1.7 kB
3
Indexable
Never
document.addEventListener('DOMContentLoaded', () => { const todoForm = document.getElementById('todoForm'); const taskInput = document.getElementById('taskInput'); const todoList = document.getElementById('todoList'); // Load existing todos from local storage let todos = JSON.parse(localStorage.getItem('todos')) || []; // Display todos const renderTodos = () => { todoList.innerHTML = ''; todos.forEach((todo, index) => { const todoCard = document.createElement('div'); todoCard.classList.add('todo-card'); todoCard.innerHTML = ` <span>${todo.task}</span> <button onclick="deleteTask(${index})">Delete</button> `; todoList.appendChild(todoCard); }); }; // Form validation and adding a new task todoForm.addEventListener('submit', (e) => { e.preventDefault(); const taskValue = taskInput.value.trim(); // Validation using RegEx (task should not be empty and min length of 3) const taskRegex = /^[A-Za-z0-9 ]{3,}$/; if (!taskRegex.test(taskValue)) { alert('Task must be at least 3 characters long and not contain special characters.'); return; } const newTask = { task: taskValue }; todos.push(newTask); localStorage.setItem('todos', JSON.stringify(todos)); taskInput.value = ''; // Clear input field renderTodos(); // Re-render the list }); // Delete task window.deleteTask = (index) => { todos.splice(index, 1); localStorage.setItem('todos', JSON.stringify(todos)); renderTodos(); }; // Initial render renderTodos(); });
Leave a Comment