Untitled
unknown
plain_text
5 days ago
2.4 kB
2
Indexable
Never
// Factory function for creating tasks function createTask(description) { return { id: Math.random().toString(36).substr(2, 9), description: description, isCompleted: false }; } // DOM Elements const todoForm = document.getElementById('todoForm'); const todoInput = document.getElementById('todoInput'); const taskList = document.getElementById('taskList'); const errorMessage = document.getElementById('error-message'); // Local Storage Key const TASKS_STORAGE_KEY = 'tasks'; // Initialize tasks array let tasks = JSON.parse(localStorage.getItem(TASKS_STORAGE_KEY)) || []; // Display tasks on load window.addEventListener('DOMContentLoaded', renderTasks); // Event listener for form submission todoForm.addEventListener('submit', (e) => { e.preventDefault(); const taskDescription = todoInput.value.trim(); // Validate input with RegEx (At least 3 characters and alphanumeric) const regex = /^[a-zA-Z0-9 ]{3,}$/; if (!regex.test(taskDescription)) { errorMessage.textContent = 'Task must be at least 3 characters and alphanumeric.'; return; } errorMessage.textContent = ''; // Clear error message // Create new task const newTask = createTask(taskDescription); tasks.push(newTask); // Save to localStorage saveTasks(); // Clear the input todoInput.value = ''; // Render tasks renderTasks(); }); // Function to render tasks on the page function renderTasks() { taskList.innerHTML = ''; // Clear existing tasks tasks.forEach(task => { const taskCard = document.createElement('div'); taskCard.classList.add('task-card'); const taskDescription = document.createElement('p'); taskDescription.textContent = task.description; const deleteButton = document.createElement('button'); deleteButton.textContent = 'Delete'; deleteButton.addEventListener('click', () => deleteTask(task.id)); taskCard.appendChild(taskDescription); taskCard.appendChild(deleteButton); taskList.appendChild(taskCard); }); } // Function to delete a task function deleteTask(id) { tasks = tasks.filter(task => task.id !== id); saveTasks(); renderTasks(); } // Function to save tasks to localStorage function saveTasks() { localStorage.setItem(TASKS_STORAGE_KEY, JSON.stringify(tasks)); }
Leave a Comment