My Submit Button does not save text from textarea - javascript

I have got problem with my button. Button is not save my text from textarea, and i do not know why.
I everything is conneted and a text shoud go properly to save.
I try look for some typo.
Console in Chrome does not show any mistakes.
I try check for some typo, but i do not find any.
terminal in VisualCode do not show any mistakes
let todoList = null;
let todoForm = null;
let todoSearch = null;
document.addEventListener('DOMContentLoaded', function() {
todoList = document.querySelector('#todoList');
todoForm = document.querySelector('#todoForm');
todoSearch = document.querySelector('#todoSearch');
todoForm.addEventListener('submit', function(e) {
e.preventDefault();
const textarea = this.querySelector('textarea');
if (textarea.value !== ' ') {
addTask(textarea.value);
textarea.value = '';
}
});
});
function addTask(text) {
const todo = document.createElement('div');
todo.classList.add("task-element");
const todoBar = document.createElement('div');
todoBar.classList.add('task-bar');
const todoDate = document.createElement('div');
todoDate.classList.add('task-bar');
const date = new Date();
const dateText = date.getDate() + '-' + (date.getMonth() + 1) + '-' + date.getHours() + ':' + date.getMinutes();
todoDate.inner = dateText;
const todoDelete = document.createElement('button');
todoDelete.classList.add('task-delete')
todoDelete.classList.add('button')
todoDelete.innerHTML = '<i class="fas fa-times-circle"></i>';
todoBar.appendChild(todoDate);
todoBar.appendChild(todoDelete);
const todoText = document.createElement('div');
todoText.classList.add('task-text');
todoText.innerText = text;
todo.appendChild(todoBar);
todo.appendChild(todoText);
todoList.append(todp);
}
document.addEventListener('DOMContentLoaded', function() {
todoList.addEventListener('click', function(e) {
console.log(e.target)
});
});
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="x-ua-compatible" content="ie=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<div class="todo-cnt">
<form class="formquest" id="todoForm">
<div class="firstplace">
<label class="form-message" name="message" for="todoMessage"><p>Podaj treść zadania</p></label>
<textarea class="input" id="input" id="todoMessage"></textarea>
</form>
</div>
<div class="button-place">
<button type="submit" class="button todo-form-button">Dodaj</button>
</div>
<section class="list-cnt">
<header class="header-list">
<h2 class="text-list">
Lista Zadań
</h2>
<form class="list-form">
<input type="search" id="todoSearch" class="search-form">
</form>
</header>
</section>
<div class="task-element">
<div class="task-bar">
<h3 class="task-date">60-80-2019 11:87</h3>
<button class="task-delete" title="Usuń zadanie">
<i class="task-time"></i>
</div>
<div class="task-text" id="todoList">
<p>Przykładowy tekst zadan dla tasku</p>
</div>
</div>
<link rel="stylesheet"type="text/css"href="projekt2.css">
<script src="projekt2.js" async defer></script>
</body>
</html>

Button outside the form
other button not closed
form closed wrongly half inside a div anyway
Spelling of todp instead of todo
I added text to the <i> because I did not load the fontawesome
let todoList = null;
let todoForm = null;
let todoSearch = null;
document.addEventListener('DOMContentLoaded', function() {
todoList = document.querySelector('#todoList');
todoForm = document.querySelector('#todoForm');
todoSearch = document.querySelector('#todoSearch');
todoForm.addEventListener('submit', function(e) {
e.preventDefault();
const textarea = this.querySelector('textarea');
if (textarea.value !== ' ') {
addTask(textarea.value);
textarea.value = '';
}
});
});
function addTask(text) {
const todo = document.createElement('div');
todo.classList.add("task-element");
const todoBar = document.createElement('div');
todoBar.classList.add('task-bar');
const todoDate = document.createElement('div');
todoDate.classList.add('task-bar');
const date = new Date();
const dateText = date.getDate() + '-' + (date.getMonth() + 1) + '-' + date.getHours() + ':' + date.getMinutes();
todoDate.inner = dateText;
const todoDelete = document.createElement('button');
todoDelete.classList.add('task-delete')
todoDelete.classList.add('button')
todoDelete.innerHTML = '<i class="fas fa-times-circle">°</i>';
todoBar.appendChild(todoDate);
todoBar.appendChild(todoDelete);
const todoText = document.createElement('div');
todoText.classList.add('task-text');
todoText.innerText = text;
todo.appendChild(todoBar);
todo.appendChild(todoText);
todoList.append(todo);
}
document.addEventListener('DOMContentLoaded', function() {
todoList.addEventListener('click', function(e) {
console.log(e.target)
});
});
<form class="formquest" id="todoForm">
<div class="todo-cnt">
<div class="firstplace">
<label class="form-message" name="message" for="todoMessage"><p>Podaj treść zadania</p></label>
<textarea class="input" id="input" id="todoMessage"></textarea>
</div>
<div class="button-place">
<button type="submit" class="button todo-form-button">Dodaj</button>
</div>
<section class="list-cnt">
<header class="header-list">
<h2 class="text-list">
Lista Zadań
</h2>
<form class="list-form">
<input type="search" id="todoSearch" class="search-form">
</form>
</header>
</section>
<div class="task-element">
<div class="task-bar">
<h3 class="task-date">60-80-2019 11:87</h3>
<button class="task-delete" title="Usuń zadanie"><i class="task-time">Task time</i></button>
<div class="task-text" id="todoList">
<p>Przykładowy tekst zadan dla tasku</p>
</div>
</div>
</div>
</div>
</form>

A submit button is supposed to be inside the form tag in order to work.
<div class="todo-cnt">
<form class="formquest" id="todoForm">
<div class="firstplace">
<label class="form-message" name="message" for="todoMessage"><p>Podaj treść zadania</p></label>
<textarea class="input" id="input" id="todoMessage"></textarea>
<div class="button-place">
<button type="submit" class="button todo-form-button">Dodaj</button>
</div>
</form>
</div>

Remember whenever you are dealing with a submit button you must make sure that the submit button is within the form which you are submitting.
<form class="formquest" id="todoForm">
<div class="firstplace">
<label class="form-message" name="message" for="todoMessage"><p>Podaj treść zadania</p></label>
<textarea class="input" id="input" id="todoMessage"></textarea>
</div>
<div class="button-place">
<button type="submit" class="button todo-form-button">Dodaj</button>
</div>
</form>
<section class="list-cnt">

Related

How can I insert elements in an array to a HTML document using Javascript?

I am trying to add the elements of a list called "taskList" made up of values I get from the input elements.
Can anyone please help me, I don't understand why the elements from the list are not showing.
var taskList = [];
var input = document.getElementById('takeInput');
var button = document.getElementById('addInput');
button.onclick = function(){
var nHTML = '';
var userEnteredText = input.value;
taskList.push(userEnteredText);
taskList.forEach(function(task){
nHTML += '<li>'+task+'</li>';
});
document.getElementsByClassName('taskLists').innerHTML = '<ul>' + nHTML + '</ul>';
}
<div class="wrapper">
<header>To-Do List</header>
<div class="taskAdder">
<input id="takeInput" type="text" placeholder="Add your new To-Do">
<button id="addInput" class="button" type="button" >➕</button>
</div>
<div class="taskLists">
</div>
<div class="footer">
<span> You have <span class="pendingTasks"></span> tasks left </span>
<button type="button" class="button">Clear All</button>
</div>
</div>
I tried checking several times but nothing is updating in the HTML document
You shouldn't append to innerHTML, instead, use createElement to make the li, then set innerHTML of that new element to input.value and use appendChild to append it to the list
var input = document.getElementById('takeInput');
var button = document.getElementById('addInput');
var tlist = document.getElementsByClassName('taskLists')[0];
button.onclick = function(){
let e = document.createElement('li');
e.innerHTML = input.value
tlist.appendChild(e)
// Optionally, clear the input field to prevent double adding the same task
input.value = '';
}
<div class="wrapper">
<header>To-Do List</header>
<div class="taskAdder">
<input id="takeInput" type="text" placeholder="Add your new To-Do">
<button id="addInput" class="button" type="button" >➕</button>
</div>
<div class="taskLists">
</div>
<div class="footer">
<span> You have <span class="pendingTasks"></span> tasks left </span>
<button type="button" class="button">Clear All</button>
</div>
</div>
The main mistake was using .getElementsByClassName like it was one element only and not a list (don't ignore the s in elements!).
Anyway I slightly refactored your code to have better strategies for each of its goals and implemented also the logic for clearing the tasks list.
var taskList = [];
var input = document.getElementById('takeInput');
var buttonAdd = document.getElementById('addInput');
var buttonClear = document.getElementById('clearInput');
var tasksList = document.getElementById('tasksList');
buttonAdd.addEventListener('click', (event)=>{
addTask(input.value);
});
buttonClear.addEventListener('click', (event)=>{
tasksList = [];
document.querySelector('#tasksList ul').remove();
});
function addTask(value){
if(taskList.length == 0){
document.getElementById('tasksList').append( document.createElement('ul') );
}
taskList.push(value);
const newLI = document.createElement('li');
newLI.innerText = value;
document.querySelector('#tasksList ul').append(newLI);
}
<body>
<div class="wrapper">
<header>To-Do List</header>
<div class="taskAdder">
<input id="takeInput" type="text" placeholder="Add your new To-Do">
<button id="addInput" class="button" type="button">➕</button>
</div>
<div id="tasksList">
</div>
<div class="footer">
<span> You have <span class="pendingTasks"></span> tasks left </span>
<button id="clearInput" type="button" class="button">Clear All</button>
</div>
</div>
</body>
you just needed to use an ID on the tasklist.
getElementsByClassName needs an index, making your question a dupe of What do querySelectorAll and getElementsBy* methods return?:
document.getElementsByClassName('taskLists')[0].innerHTML
That said, here is a full version using recommended eventListener and IDs where relevant.
let tasks = [];
const taskList = document.getElementById('taskLists')
const input = document.getElementById('takeInput');
const add = document.getElementById('addInput');
const pendingTasks = document.getElementById('pendingTasks');
const clear = document.getElementById('clear');
const showTasks = () => {
taskList.innerHTML = `<ul>${tasks.map(task => `<li>${task}</li>`).join('')}</ul>`;
pendingTasks.textContent = `${tasks.length} task${tasks.length != 1 ? "s" : ""}`;
};
add.addEventListener('click', () => {
var userEnteredText = input.value;
tasks.push(userEnteredText);
showTasks();
});
clear.addEventListener('click', () => {
tasks = [];
showTasks();
});
taskList.addEventListener('click', (e) => {
const tgt = e.target.closest('li');
if (!tgt) return; // not a task
const task = tgt.textContent;
tgt.remove()
tasks = tasks.filter(currentTask => currentTask != task); // remove from list
showTasks()
});
showTasks(); //init
<div class="wrapper">
<header>To-Do List</header>
<div class="taskAdder">
<input id="takeInput" type="text" placeholder="Add your new To-Do">
<button id="addInput" class="button" type="button">➕</button>
</div>
<div id="taskLists"></div>
<div class="footer">
<span> You have <span id="pendingTasks"></span> left </span>
<button type="button" id="clear">Clear All</button>
</div>
</div>

Arrays object property is not updating

this is my first post here. Please excuse my poor code, I will try my best to describe my issue.
I'm building a Library app from Odin Project. Currently I'm able to create an object with values I'm inputting in a popup form. Created object is being displayed on the screen with correct values as intended.
My goal is to update Read status in a myLibrary array when I click on a button. I was able to update the text content on the button with a click, unfortunately I have no idea how to update a read value in an array for the created object.
I would really appreciate any suggestions.
Thank you for your time
let myLibrary = [];
const registerBook = document.getElementById("registerBook");
const title = document.getElementById("title");
const author = document.getElementById("author");
const pages = document.getElementById("pages");
let read = document.getElementById("read-btn");
let form = document.getElementById("bookForm");
let optionYes = document.getElementById("option-yes");
let optionNo = document.getElementById("option-no");
function openForm() {
document.getElementById("bookForm").style.display = "block";
}
function closeForm() {
document.getElementById("bookForm").style.display = "none";
}
registerBook.addEventListener("click", function() {
myLibrary.push({
title: title.value,
author: author.value,
pages: pages.value,
read: read.value,
})
renderBooks();
console.log(myLibrary);
})
function renderBooks() {
let bookShelf = document.querySelector('#bookShelf');
let bookCover = document.createElement('div');
bookCover.classList.add('bookCover');
bookShelf.appendChild(bookCover);
let deleteCard = document.createElement('div');
deleteCard.classList.add('delete-card');
deleteCard.id = "deleteCard";
bookCover.append(deleteCard);
let bookTitleTag = document.createElement('div');
bookTitleTag.classList.add('book-title-tag');
bookCover.append(bookTitleTag);
bookTitleTag.textContent = 'Book title:';
let bookTitle = document.createElement('div');
bookTitle.classList.add('book-title');
bookCover.append(bookTitle);
let bookAuthorTag = document.createElement('div');
bookAuthorTag.classList.add('book-author-tag');
bookCover.append(bookAuthorTag);
bookAuthorTag.textContent = 'Book author:';
let bookAuthor = document.createElement('div');
bookAuthor.classList.add('book-author');
bookCover.append(bookAuthor);
let bookPagesTag = document.createElement('div');
bookPagesTag.classList.add('book-pages-tag');
bookCover.append(bookPagesTag);
bookPagesTag.textContent = 'No of pages:';
let bookPages = document.createElement('div');
bookPages.classList.add('book-pages');
bookCover.append(bookPages);
let bookStatusTag = document.createElement('div');
bookStatusTag.classList.add('book-pages-tag');
bookCover.append(bookStatusTag);
bookStatusTag.textContent = 'Have you read the book?:';
let bookStatus = document.createElement('button');
bookStatus.classList.add('book-status-btn');
bookStatus.id = 'book-status-btn';
bookCover.append(bookStatus);
bookTitle.textContent = title.value;
bookAuthor.textContent = author.value;
bookPages.textContent = pages.value;
bookStatus.textContent = read.value;
/*Book status in card is updated */
bookStatus.addEventListener("click", () => {
if (bookStatus.textContent === 'Yes') {
bookStatus.textContent = 'No'
} else {
if (bookStatus.textContent === 'No') {
bookStatus.textContent = 'Yes'
}
}
});
/* Trying to update array */
bookStatus.addEventListener("click", () => {
if (bookCover.read === 'Yes') {
bookCover.read = 'No'
} else {
if (bookCover.read === 'No') {
bookCover.read = 'Yes'
}
}
console.log(myLibrary);
});
deleteCard.addEventListener("click", () => {
bookShelf.removeChild(bookCover);
myLibrary.splice(bookCover, 1);
});
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="styles.css">
<script defer src="index.js"></script>
<title>Library</title>
</head>
<body>
<div class="wrapper">
<div class="header">
<div class="logo">Library</div>
<div class="buttons">
<div class="add-book-btn" id="addBookBtn" onclick="openForm()">Add Book</div>
<!--<div class="login-btn">Log in</div> -->
</div>
</div>
<div class="main">
<div class="form-popup" id="bookForm">
<form action="/action_page.php" onsubmit="event.preventDefault()" class="form-container">
<div class="form-popup-close" onclick="closeForm()"></div>
<h1>Add Book</h1>
<label for="title"><b>Book title</b></label>
<input type="text" id="title" placeholder="Enter book title" name="title" required>
<label for="author"><b>Author</b></label>
<input type="text" id="author" placeholder="Enter author name" name="author">
<label for="pages"><b>No. of pages</b></label>
<input type="number" id="pages" placeholder="Number of pages" name="pages">
<div class="form-bot">
<p>Have you read it?</p>
<select name="read" id="read-btn">
<option id="option-yes" value="Yes">Yes</option>
<option id="option-no" value="No">No</option>
</select>
</div>
<button type="button" class="btn" id="registerBook" onclick="closeForm()">Register Book</button>
</form>
</div>
<div id="bookShelf"></div>
</div>
</div>
</body>
</html>
You can get the title from the bbookTitle DIV, and search the array for that title. Then you can toggle the read property.
let myLibrary = [];
const registerBook = document.getElementById("registerBook");
const title = document.getElementById("title");
const author = document.getElementById("author");
const pages = document.getElementById("pages");
let read = document.getElementById("read-btn");
let form = document.getElementById("bookForm");
let optionYes = document.getElementById("option-yes");
let optionNo = document.getElementById("option-no");
function openForm() {
document.getElementById("bookForm").style.display = "block";
}
function closeForm() {
document.getElementById("bookForm").style.display = "none";
}
registerBook.addEventListener("click", function() {
myLibrary.push({
title: title.value,
author: author.value,
pages: pages.value,
read: read.value,
})
renderBooks();
console.log(myLibrary);
})
function renderBooks() {
let bookShelf = document.querySelector('#bookShelf');
let bookCover = document.createElement('div');
bookCover.classList.add('bookCover');
bookShelf.appendChild(bookCover);
let deleteCard = document.createElement('div');
deleteCard.classList.add('delete-card');
deleteCard.id = "deleteCard";
bookCover.append(deleteCard);
let bookTitleTag = document.createElement('div');
bookTitleTag.classList.add('book-title-tag');
bookCover.append(bookTitleTag);
bookTitleTag.textContent = 'Book title:';
let bookTitle = document.createElement('div');
bookTitle.classList.add('book-title');
bookCover.append(bookTitle);
let bookAuthorTag = document.createElement('div');
bookAuthorTag.classList.add('book-author-tag');
bookCover.append(bookAuthorTag);
bookAuthorTag.textContent = 'Book author:';
let bookAuthor = document.createElement('div');
bookAuthor.classList.add('book-author');
bookCover.append(bookAuthor);
let bookPagesTag = document.createElement('div');
bookPagesTag.classList.add('book-pages-tag');
bookCover.append(bookPagesTag);
bookPagesTag.textContent = 'No of pages:';
let bookPages = document.createElement('div');
bookPages.classList.add('book-pages');
bookCover.append(bookPages);
let bookStatusTag = document.createElement('div');
bookStatusTag.classList.add('book-pages-tag');
bookCover.append(bookStatusTag);
bookStatusTag.textContent = 'Have you read the book?:';
let bookStatus = document.createElement('button');
bookStatus.classList.add('book-status-btn');
bookStatus.id = 'book-status-btn';
bookCover.append(bookStatus);
bookTitle.textContent = title.value;
bookAuthor.textContent = author.value;
bookPages.textContent = pages.value;
bookStatus.textContent = read.value;
/*Book status in card is updated */
bookStatus.addEventListener("click", () => {
if (bookStatus.textContent === 'Yes') {
bookStatus.textContent = 'No'
} else {
if (bookStatus.textContent === 'No') {
bookStatus.textContent = 'Yes'
}
}
});
/* Trying to update array */
bookStatus.addEventListener("click", () => {
let title = bookTitle.textContent;
let book = myLibrary.find(book => book.title === title);
if (book) {
book.read = book.read === 'Yes' ? 'No' : 'Yes';
bookStatus.textContent = book.read;
}
console.log(myLibrary);
});
deleteCard.addEventListener("click", () => {
bookShelf.removeChild(bookCover);
myLibrary.splice(bookCover, 1);
});
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="styles.css">
<script defer src="index.js"></script>
<title>Library</title>
</head>
<body>
<div class="wrapper">
<div class="header">
<div class="logo">Library</div>
<div class="buttons">
<div class="add-book-btn" id="addBookBtn" onclick="openForm()">Add Book</div>
<!--<div class="login-btn">Log in</div> -->
</div>
</div>
<div class="main">
<div class="form-popup" id="bookForm">
<form action="/action_page.php" onsubmit="event.preventDefault()" class="form-container">
<div class="form-popup-close" onclick="closeForm()"></div>
<h1>Add Book</h1>
<label for="title"><b>Book title</b></label>
<input type="text" id="title" placeholder="Enter book title" name="title" required>
<label for="author"><b>Author</b></label>
<input type="text" id="author" placeholder="Enter author name" name="author">
<label for="pages"><b>No. of pages</b></label>
<input type="number" id="pages" placeholder="Number of pages" name="pages">
<div class="form-bot">
<p>Have you read it?</p>
<select name="read" id="read-btn">
<option id="option-yes" value="Yes">Yes</option>
<option id="option-no" value="No">No</option>
</select>
</div>
<button type="button" class="btn" id="registerBook" onclick="closeForm()">Register Book</button>
</form>
</div>
<div id="bookShelf"></div>
</div>
</div>
</body>
</html>

How do I target my class task for the event Listener to Handle?

My buttons for edit delete and save are not working and that is because the event listener is passing an element that has nothing in it, but I want to target the class <div class="task" date-id = "${id}"> for the event listener.
This is what is wrong:
elements.list.addEventListener('click',event => the elements.list is wrong as it is not holding anything. But I would like to target the <div class="task" date-id = "${id}"> for the eventEventListener.
Please see the full code so you have a better idea:
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>To-do App</title>
<script src="js/main.js" defer></script>
<script src="js/dateTime.js" defer></script>
<link rel="stylesheet" href="css/main.css" />
</head>
<body>
<div class="header">
<h1>To-Do List</h1>
<div class="time">
<div class="dateTime"></div>
<div class="day"></div>
</div>
</div>
<form id="new-task-form">
<div class="add-task">
<input type="text" name="new-task-input" id="new-task-input" placeholder="What do you have planned?" />
<input type="date" id="calendar">
</div>
<input type="submit" id="new-task-submit" value="Add task" />
</form>
</header>
<main>
<section class="task-list">
<h2>Tasks</h2>
<div id="tasks">
<!--<button class = "sort">Sort</button>
<div class="task">
<div class="content">
<input
type="text"
class="text"
value="A new task"
readonly>
</div>
<div class="actions">
<button class="edit">Edit</button>
<button class="delete">Delete</button>
</div>
</div>-->
</div>
</section>
</main>
</body>
</html>
JS
/************************************
* creates objct of elements needed *
************************************/
const elements = {
form: document.querySelector("#new-task-form"),
input: document.querySelector("#new-task-input"),
list: document.querySelector("#tasks"),
cal: document.querySelector("#calendar")
}
/****************************
* Generates an ID for task *
****************************/
const createId = () => `${Math.floor(Math.random() * 10000)}-${new Date().getTime()}`
/**********************************************
* function that creates the HTML elements *
**********************************************/
const createTask = () => {
const id = createId()
const task = elements.input.value;
const date = elements.cal.value;
if(!task && !date) return alert("Please fill in task and select date");
if(!task) return alert("Please fill in task");
if(!date) return alert("Please select date");
const tasks = document.createElement("div");
tasks.innerHTML = `
<button class = "sort">Sort</button>
<div class="task" data-id = "${id}">
<div class="content">
<input type ="checkbox" class="tick">
<input type ="text" class = "text" id = "text" readonly>${task}
<label class = "due-date" for ="text">${date}</label>
<input type ="date" class = "date" id = "date">
</div>
<div class = "actions">
<button class="edit" data-id="${id}">Edit</button>
<button class="delete" data-id="${id}">Delete</button>
</div>
</div>
`
elements.list.appendChild(tasks)
return tasks
}
/**************************************************************
* Event that listens for the edit,save and delete buttons *
**************************************************************/
elements.list.addEventListener('click',event => {
const {target} = event
const {id} = target.dataset
const task = id ? document.querySelector('[data-id="${id}"]'):null;
const type = {
edit: event.target.classList.contains('edit'),
delete: event.target.classList.contains('delete')
}
const isFromSaveLabel = target.innerText.toLowerCase() === 'save'
if(task && type.edit && isFromSaveLabel){
const text = task.querySelector('.text')
target.innerText = 'Edit'
text.addAttribute('readonly')
return
};
if(task && type.edit){
const text = task.querySelector('.text')
target.innerText = 'save'
text.removeAttribute('readonly')
text.focus()
return
};
if(task && type.delete){
return
}
});
/*******************************************************************
* Submits the HTML elements to have the lists submitted and created*
*******************************************************************/
const submitHandler = (event) =>{
event.preventDefault();
createTask();
}
elements.form.addEventListener("submit", submitHandler);
I have been asking a lot about this on the platform, but I realized I have been asking the wrong question. As mentioned above I need the event listener to target the <div class="task" date-id = "${id}"> that has been created with const tasks = document.createElement("div");
The reason is when you click on add task it creates a new <div class="task" date-id = "${id}"> for example ```````
with the contents class and everything in there.
PS: Apologies for the long-winded code, it's necessary so that you get the full picture of the issue and question
Could it be beacause you used "date-id" on tasks.innerHTML, but use "data-id" on
const task = id ? document.querySelector('[data-id="${id}"]'):null;
Okay, I found some issues in the event listener:
the queryselector is not a template literal, so ${id} doesn't work.
"addAttribute" is wrong. "setAttribute" is the correct one.
Edit and save works after these are fixed.
/**************************************************************
* Event that listens for the edit,save and delete buttons *
**************************************************************/
elements.list.addEventListener('click',event => {
const {target} = event
const {id} = target.dataset
const task = id ? document.querySelector(`[data-id="${id}"]`):null;
const type = {
edit: event.target.classList.contains('edit'),
delete: event.target.classList.contains('delete')
}
const isFromSaveLabel = target.innerText.toLowerCase() === 'save'
if(task && type.edit && isFromSaveLabel){
const text = task.querySelector('.text')
target.innerText = 'Edit'
text.setAttribute('readonly', 'true')
return
};
if(task && type.edit){
const text = task.querySelector('.text')
target.innerText = 'save'
text.removeAttribute('readonly')
text.focus()
return
};
if(task && type.delete){
return
}
});
And for the error, it is probably a bug in the extension.

Can't remove local storage elements

I have a simple to do application with local storage. In my app user can create unordered list with new tasks. Last element in this app is local storage. I have a problem with this functionality.
Before I save the items in localstorage I can delete them using the button. I don't know why but it doesn't works after saving elements.
Any idea how can I fix it?
My code:
const first= document.getElementById("first");
const second= document.getElementById("second");
function addList(e) {
const newElement = document.createElement("li");
newElement.innerHTML = first.value + second.value;
}
newElement.innerHTML += "<button> X </button>";
ul.appendChild(newElement);
store();
newElement.querySelector("button").addEventListener("click", removeElement);
}
function removeElement(e) {
e.target.parentNode.remove();
}
function store() {
window.localStorage.myitems = ul.innerHTML;
}
function getValues() {
let storedValues = window.localStorage.myitems;
if(storedValues) {
ul.innerHTML = storedValues;
ul.querySelector("button").addEventListener("click", removeElement);
}
}
getValues();
<div class="container">
<form>
<input type="text" id="first" name="artist" placeholder="Artist" />
<input type="text" id="second" name="title" placeholder="Song title" />
<button type="button" onclick="addList(event)">Add task</button>
</form>
</div>
<div class="li-elements">
<ul class="list"></ul>
</div>
Looks like you were just missing a few small things in ur code. You were not properly adding the removeElement event listener when loading from localStorage, and you were not properly updating localStorage. I have updated ur code so it works.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<div class="container">
<form>
<input type="text" id="first" name="artist" placeholder="Artist" />
<input type="text" id="second" name="title" placeholder="Song title" />
<button type="button" onclick="addList(event)">Add task</button>
</form>
</div>
<div class="li-elements">
<ul id="list" class="list"></ul>
</div>
<script>
function addList(e) {
const first = document.getElementById("first");
const second = document.getElementById("second");
const newElement = document.createElement("li");
newElement.innerHTML = first.value + second.value;
newElement.innerHTML += "<button> X </button>";
document.getElementById("list").appendChild(newElement);
store();
newElement.querySelector("button").addEventListener("click", removeElement);
}
function removeElement(e) {
e.target.parentNode.remove();
store();
}
function store() {
window.localStorage["myitems"] = document.getElementById("list").innerHTML;
}
function getValues() {
let storedValues = window.localStorage["myitems"];
if (storedValues) {
let ul = document.getElementById("list");
ul.innerHTML = storedValues;
for (i = 0; i < ul.childNodes.length; i++) {
ul.childNodes[i].querySelector("button").addEventListener("click", removeElement);
}
}
}
getValues();
</script>
</body>
</html>

What will be the Javascript code for this for changing the ID of each tag while making a clone every time?

I want to clone the template and show it to the <div id= "wrapper"> with different ID every time I make a clone. When I press the add-new-project button a new template is shown with different "ID" every time.
Javascript code:
$("document").ready(function () {
var cloneCntr = 1;
var i = 0;
$("#projectData").on('click', function () {
$('template').children().each(function () {
this.id = this.id+ this.i;
});
var temp = document.getElementsByTagName("template")[0];
var clon = temp.content.cloneNode(true);
i++;
$('#wrapper').append(clon);
});
});
Html code:
<form id="projectForm">
<div class="container">
////// ---------------------code-------//// <br>
<br>
<h4>Project Experience</h4>
<hr>
<template id="template">
<br>
<br>
<div class="form-row">
---------Template Code-------
</div>
</div>
<hr>
</template>
</div>
<div id="wrapper" class="container">
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
<div class="container">
<button type="button" id="projectData" class="btn btn-primary">Add New Project</button>
</div>
</body>
</html>
I want to replace every tag "id" in the template, every time when I make a clone of this.
Here's an example of how this could work for you.
See a demo here: https://jsfiddle.net/o76pqxyw/
Here's a screenshare, showing how the IDs change: https://www.loom.com/share/4a1556c4bb5c4422ad1d4b20a12a638a
HTML
<div id="template-form">
<p><label>First Name</label> <input type="text" id="first-name" /></p>
<p><label>Last Name</label> <input type="text" id="last-name" /></p>
</div>
<button id="btn">Add New User</button>
<div id="container"></div>
Javascript
const button = $('#btn');
const target = $('#container');
let counter = 0;
$(button).on('click', () => {
const template = $('#template-form');
const copy = $(template).clone();
counter++;
const elements = $(copy).find('input');
$(elements).each(function(index) {
const currentId = $(this).attr('id');
const newId = currentId + '-' + counter;
$(this).attr('id', newId);
});
$(target).append(copy);
})

Categories