Remove appended element - javascript

When I type something in the first box, and click Next, the word I typed is inserted on my page. However, if I click Back and then click Next again, it is printed a second time.
I want the keyword appended after I've clicked Next to be deleted if I click Back so that if I click Next again it is printed only once (and updated if I have made any edit).
document.addEventListener("DOMContentLoaded", function() {
var stepOne = document.getElementsByClassName("step-1");
var stepTwo = document.getElementsByClassName("step-2");
var nextButton = document.getElementsByClassName("next");
var backButton = document.getElementsByClassName("back");
nextButton[0].onclick = function() {
stepOne[0].style.display = "none";
stepTwo[0].style.display = "block";
var inputKeyword = document.getElementById("inputJobTitle").value;
var newKeyword = document.createElement("p");
newKeyword.setAttribute("id", "retrievedField-1");
newKeyword.setAttribute("class", "retrievedFieldName");
newKeyword.innerText = inputKeyword;
newKeyword.setAttribute("id", "retrievedField-1");
newKeyword.setAttribute("class", "retrievedFieldName");
document.getElementById("retrievedFields").appendChild(newKeyword);
}
backButton[0].onclick = function() {
stepOne[0].style.display = "block";
stepTwo[0].style.display = "none";
}
})
.step-1 {
display: block;
}
.step-2 {
display: none;
}
<!--STEP 1-->
<div class="main step-1">
<div class="tab" id="tab-1">
<div class="inputFields">
<p id="jobtitle" class="inputFieldName">Job title</p>
<input type="search" id="inputJobTitle" class="inputBar" />
<p class="and">AND</p>
</div>
<div class="button">
<button class="next">Next ></button>
</div>
</div>
</div>
<!--STEP 2-->
<div class="main step-2">
<div class="tab" id="tab-1">
<div class="inputFields">
<div id="retrievedFields"></div>
<input type="search" class="inputBarAlternative" />
<div class="add">
<button class="addButton">+ Add Keyword</button>
<p id="addKeyword">
Add a skill or keyword that must be in your search results
</p>
</div>
</div>
<div class="buttons">
<button class="back">Back</button>
<button class="next">Next</button>
</div>
</div>
</div>
</body>

Each new click on the next button will trigger an append. So you just have to do the opposite of an append on the click on back. Just add this line in your onclick:
document.getElementById("retrievedFields").removeChild(document.getElementById("retrievedFields").lastElementChild);

You could also check to see if the element exists before you create it..
nextButton[0].onclick = function() {
stepOne[0].style.display = "none";
stepTwo[0].style.display = "block";
var inputKeyword = document.getElementById("inputJobTitle").value;
var newKeyword = document.getElementById("retrievedField-1")
if (!newKeyword) {
newKeyword = document.createElement("p");
newKeyword.setAttribute("id", "retrievedField-1");
newKeyword.setAttribute("class", "retrievedFieldName");
document.getElementById("retrievedFields").appendChild(newKeyword);
}
newKeyword.innerText = inputKeyword;
}

Related

Can't delete div's with new added buttons

after I keep creating new DIVs with my javascript functions, the new ones don't delete themselves.
My codes creates a post it div which gives info about title, author, and pages, and a X button that when you press it, it deletes it.
It works for my first 4 HTML examples, but not with the newly added divs from javascript.
const container = document.querySelector('.right');
let removeButtons = document.querySelectorAll('.remove');
let removeButtonsArray = Array.prototype.slice.call(removeButtons);
let bookNum = 4;
function addBook() {
const titleAdd = document.getElementById('title-add').value;
const readAdd = document.getElementById('read-add').value;
const totalAdd = document.getElementById('total-add').value;
if (titleAdd == '' || readAdd == '' || totalAdd == '') {
alert('Complete all of the boxes');
return;
} else if (readAdd > totalAdd) {
alert('why are you lying? =[[');
return;
}
const book = document.createElement('div');
book.classList.add('book');
container.appendChild(book);
const xButton = document.createElement('button');
xButton.classList.add('remove');
book.appendChild(xButton);
xButton.innerHTML = 'X';
const title = document.createElement('h2');
book.appendChild(title);
title.innerHTML = titleAdd;
const author = document.createElement('h3');
book.appendChild(author);
author.innerHTML = document.getElementById('author-add').value;
const pages = document.createElement('h3');
book.appendChild(pages);
const pagesNumber = readAdd + '/' + totalAdd;
pages.classList.add('page-num')
pages.innerHTML = pagesNumber;
bookNum++;
removeButtons = document.querySelectorAll('.remove');
removeButtonsArray = Array.prototype.slice.call(removeButtons);
}
const button = document.querySelector('.add');
button.onclick = addBook;
removeButtonsArray.forEach(removeButton => removeButton.addEventListener('click', function() {
const remove = removeButtonsArray.indexOf(removeButton);
removeButtonsArray.splice(remove, 1);
document.querySelector('.book').remove();
bookNum--;
}));
<div class="container">
<div class="left">
<div class="title-add">
<h2>Title:</h2>
<input type="text" id="title-add" name="title-add" max="30">
</div>
<div class="author-add">
<h2>Author:</h2>
<input type="text" id="author-add" name="author-add" max="30">
</div>
<div class="pages">
<div class="pages-read">
<h3>Pages read:</h3>
<input type="number" id="read-add" min="0" name="read">
</div>
<div class="pages-total">
<h3>Total pages:</h3>
<input type="number" id="total-add" min="1" name="total">
</div>
</div>
<button class="add">Add book</button>
</div>
<div class="right">
<div class="book">
<button class="remove">X</button>
<h2 class="title">muie</h2 >
<h3 class="author">Csokmai Robert123</h3>
<h3 class="page-num">31/316</h3>
</div>
<div class="book">
<button class="remove">X</button>
<h2>muie</h2 >
<h3>Csokmai Robert</h3>
<h3 class="page-num">31/316</h3>
</div>
<div class="book">
<button class="remove">X</button>
<h2>muie</h2 >
<h3>Csokmai Robert</h3>
<h3 class="page-num">31/316</h3>
</div>
<div class="book">
<button class="remove">X</button>
<h2>muie</h2 >
<h3>Csokmai Robert</h3>
<h3 class="page-num">31/316</h3>
</div>
</div>
</div>
I tried everything but I just don't know how to fix it
Problems:
There are a few Problems with your code:
Delete function doesn't actually work, because every time you are just removing the first element which has book class. document.querySelector('.book').remove();
The reason the Delete button for Dynamically added books was not working is because this bit of code removeButtonsArray.forEach(removeButton => removeButton.addEventListener was executed only on first execution. So, newly added buttons weren't getting the Event Listener registered for them.
Solutions:
Delete functionality can be easily handled by targeting the parentElement of the Delete Button which was clicked.
For the Dynamically added Books' Delete Functionality, We need to register the click Event Listener for each one of them during creation.
const container = document.querySelector('.right');
let removeButtons = document.querySelectorAll('.remove');
let bookNum = 4;
function addBook() {
const titleAdd = document.getElementById('title-add').value;
const readAdd = document.getElementById('read-add').value;
const totalAdd = document.getElementById('total-add').value;
if (titleAdd == '' || readAdd == '' || totalAdd == '') {
alert('Complete all of the boxes');
return;
} else if (readAdd > totalAdd) {
alert('why are you lying? =[[');
return;
}
const book = document.createElement('div');
book.classList.add('book');
container.appendChild(book);
const xButton = document.createElement('button');
xButton.classList.add('remove');
book.appendChild(xButton);
xButton.innerHTML = 'X';
const title = document.createElement('h2');
book.appendChild(title);
title.innerHTML = titleAdd;
const author = document.createElement('h3');
book.appendChild(author);
author.innerHTML = document.getElementById('author-add').value;
const pages = document.createElement('h3');
book.appendChild(pages);
const pagesNumber = readAdd + '/' + totalAdd;
pages.classList.add('page-num')
pages.innerHTML = pagesNumber;
bookNum++;
// Adding Click Event to new Books Delete Button
xButton.addEventListener("click", removeBook);
}
const button = document.querySelector('.add');
button.onclick = addBook;
// Function for Removing Book
function removeBook(e) {
// Since we are getting the Delete Buttons event as Frunction Argument
// We can get access to it's parentElement i.e., the target Book Div
e.target.parentElement.remove();
bookNum--;
}
removeButtons.forEach(removeButton => removeButton.addEventListener('click', removeBook));
<div class="container">
<div class="left">
<div class="title-add">
<h2>Title:</h2>
<input type="text" id="title-add" name="title-add" max="30">
</div>
<div class="author-add">
<h2>Author:</h2>
<input type="text" id="author-add" name="author-add" max="30">
</div>
<div class="pages">
<div class="pages-read">
<h3>Pages read:</h3>
<input type="number" id="read-add" min="0" name="read">
</div>
<div class="pages-total">
<h3>Total pages:</h3>
<input type="number" id="total-add" min="1" name="total">
</div>
</div>
<button class="add">Add book</button>
</div>
<div class="right">
<div class="book">
<button class="remove">X</button>
<h2 class="title">muie</h2>
<h3 class="author">Csokmai Robert123</h3>
<h3 class="page-num">31/316</h3>
</div>
<div class="book">
<button class="remove">X</button>
<h2>muie</h2>
<h3>Csokmai Robert</h3>
<h3 class="page-num">31/317</h3>
</div>
<div class="book">
<button class="remove">X</button>
<h2>muie</h2>
<h3>Csokmai Robert</h3>
<h3 class="page-num">31/315</h3>
</div>
<div class="book">
<button class="remove">X</button>
<h2>muie</h2>
<h3>Csokmai Robert</h3>
<h3 class="page-num">31/314</h3>
</div>
</div>
</div>

Appended elements getting removed by HTML

I am trying to create a TO DO List application. In this application when I click submit button of the formlayer, a new eventcard with all the data should be appended in the events div.
function reveal() {
document.getElementById("layer1").style.display = "block";
document.getElementById("formlayer").style.display = "block";
}
function hide() {
document.getElementById("layer1").style.display = "none";
document.getElementById("formlayer").style.display = "none";
}
function addEvent() {
document.getElementById("layer1").style.display = "none";
document.getElementById("formlayer").style.display = "none";
let title = document.getElementById("ftitle").value;
let time = document.getElementById("ftime").value;
let desc = document.getElementById("fdesc").value;
// this will create the card
let card = document.createElement("div");
card.classList.add("eventcard");
//title div
let cardtitle = document.createElement("div");
cardtitle.classList.add("eventtitle");
cardtitle.innerHTML = title;
card.appendChild(cardtitle);
//time div
let cardtime = document.createElement("div");
cardtime.classList.add("eventtime");
cardtime.innerHTML = time;
card.appendChild(cardtime);
//desc div
let carddesc = document.createElement("div");
carddesc.classList.add("eventdesc");
carddesc.innerHTML = desc;
card.appendChild(carddesc);
// del button
let cardbtn = document.createElement("button");
cardbtn.classList.add("delete");
cardbtn.innerHTML = "Delete";
card.appendChild(cardbtn);
// adding card to events
document.getElementById("events").appendChild(card);
}
<div id="container">
<div id="title">To Do List</div>
<div id="events">
<div class="eventcard">
<div class="eventtitle">Meeting</div>
<div class="eventtime">10:00 AM</div>
<div class="eventdesc">The meeting regarding the discussion of company sales</div>
<button class="delete">Delete</button>
</div>
</div>
<div id="addbtn" onclick="reveal()">Add Events</div>
</div>
<div id="layer1"></div>
<div id="formlayer">
<div id="text">Event Details</div>
<form>
<label for="Title">Event Title: </label>
<input type="text" name="ftitle" id="ftitle"> <br><br>
<label for="Time">Event Time: </label>
<input type="text" name="ftime" id="ftime"> <br><br>
<label for="Desc">Event Description: </label>
<input type="text" name="fdesc" id="fdesc"> <br>
<button class="fbut" onclick="addEvent()">Submit</button>
<button class="fbut" onclick="hide()">Close</button>
</form>
</div>
However, when I fill up the details in the form and click submit button, the new eventcard gets appended in the events div for a split second and that too with all the correct information and styling, but then automatically gets deleted for some reason. Why it is getting deleted? I have also tried placing the script in <head> and after the </body> hoping that would work but it doesn't.
Could you guys please point out where I am doing wrong? Also I am doing this on Firefox browser (it might be related).
Add type="button" to your two buttons in the form, otherwise they will submit the form. This will cause a reload, so you lose your dynamic updates.
<button type="button" class="fbut" onclick="addEvent()">Submit</button>
<button type="button" class="fbut" onclick="hide()">Close</button>

How can I add elements in JS to certain divs

How do I put the created input into the other div in situation I presented below? If I introduce divs in js like this - '<div class="monday_input"><input type="button" class="remove_button" value="-" onclick="removeMon(this)" /></div>' removing the whole element is not working for some reason in this specific case. Answering the question. No I cannot create div in parent in html because input won't magically suit to created div . Please help me somehow, thank you!
HTML:
<div class="day">
<div class="day_info">
<p>Monday</p>
</div>
<div class="add">
<div class="button" onclick="add_monday()">
<i class="fas fa-plus" id="plus"></i>
</div>
</div>
<div style="clear:both"></div>
</div>
<div id="mon">
<div style="clear:both"></div>
</div>
JavaScript:
Function to adding:
function add_monday() {
if (monday_sub_count < 5) {
monday_sub_count++;
{
const mon = document.createElement('div');
mon.className = 'subcategory';
mon.innerHTML = '<textarea name="monday'+monday_id_count+'" placeholder="Type anything you want here" class="subcategory_text"></textarea><input type="button" class="remove_button" value="-" onclick="removeMon(this)" />';
monday_id_count++;
document.getElementById('mon').appendChild(mon);
}
}
}
Function to removing:
function removeMon(mon) {
document.getElementById('mon').removeChild(mon.parentNode);
monday_sub_count--;
monday_id_count--;
};
with your own HTML
function add_monday() {
var monday_sub_count = 0;
var a;
while (monday_sub_count < 5) {
a = '<div><textarea name="monday'+monday_id_count+'" placeholder="Type anything you want here" class="subcategory_text"></textarea><input type="button" class="remove_button" value="-" onclick="removeMon(this)" /></div>';
monday_sub_count++;
$('#mon').append(a);
}
}
Here is working, "proper" version of your code. I think your problem may come from over-complicating the removal process.
function add_monday()
{
let monday_count = 0;
// Use DocumentFragment for marginal optimizations
let fragment = new DocumentFragment();
while(monday_count < 5)
{
let monday = document.createElement('div');
monday.classList.add('subcategory');
let textarea = document.createElement('textarea');
textarea.classList.add('subcategory_text');
textarea.name = "monday_"+monday_count;
textarea.placeholder = "Type anything you want here";
let removeBtn = document.createElement('input');
removeBtn.type = "button";
removeBtn.classList.add('remove_button');
removeBtn.value = "-";
removeBtn.addEventListener('click', removeMon.bind(null, removeBtn));
monday.append(textarea, removeBtn);
fragment.appendChild(monday);
monday_count++;
}
document.getElementById('mon').appendChild(fragment);
}
function removeMon(button)
{
button.parentElement.remove();
}
I simplified your script a little and changed your name attributes: Instead of assigning individual names I simply gave all textareas the name monday[]. When posting this to a PHP page the values will be pushed into an array with the same name and in case you want to harvest the values with JavaScript, then this can be done easily too.
function add_monday(){
$("#mon").append('<div><textarea name="monday[]" placeholder="Type anything you want here"></textarea><input type="button" value="-"/></div>'.repeat(5))
}
$("#mon").on("click","input[type=button]",function(){$(this).parent(). remove()})
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<div class="day">
<div class="day_info">
<p>Monday</p>
</div>
<div class="add">
<div class="button" onclick="add_monday()">
<i class="fas fa-plus" id="plus">click here to add fields</i>
</div>
</div>
<div style="clear:both"></div>
</div>
<div id="mon">
<div style="clear:both"></div>
</div>
And here a non-jQuery version:
const ad=document.querySelector(".alldays");
ad.innerHTML=
"Mon,Tues,Wednes,Thurs,Fri,Satur,Sun".split(",").map(d=>`
<div class="day">
<div class="day_info"><p>${d}day</p></div>
<div class="add">
<div class="button">
<i class="fas fa-plus" id="plus">click here to add fields</i>
</div>
</div>
<div style="clear:both"></div>
</div>
<div id="${d.toLowerCase().substr(0,3)}">
<div style="clear:both"></div>
</div>`).join("");
function add2day(el,n){
const wd=el.closest(".day"),
d=wd.querySelector("p").textContent.toLowerCase(),
html=`<textarea name="${d.toLowerCase()}[]" placeholder="Type anything you want here"></textarea><input type="button" value="-"/>`;
while (n--) {
let div= document.createElement("div");
div.innerHTML=html;
wd.nextElementSibling.appendChild(div);
}
}
ad.addEventListener("click",function(ev){
const el=ev.target;
switch(el.tagName){
case "INPUT": // remove field
el.parentNode.remove(); break;
case "I": // add new fields
add2day(el,3); break;
}
})
<div class="alldays"></div>
I extended the second script to make it work for any day of the week.

List Items are showing up inside my submit button in to-do app

My List items are showing up inside of my submit button when I submit a new task.
EXPECTATION: when the submit button is clicked a new task should show up in a task list inside the .
ACTUAL: submit button is clicked, a new task is made inside of the submit button.
<body>
<div class="container">
<h1>TO DO LIST</h1>
<form id="taskForm">
<input id="taskInput"></input>
<button type="button" id="taskButton" onclick="taskList()">
Click Here</buton>
</form>
</div>
<div>
<ul id="taskLister"></ul>
</div>
<script src=script.js></script>
</body>
function taskList() {
let item = document.getElementById("taskInput").value;
let text = document.createTextNode(item);
let newTask = document.createElement("li");
let deleteTask = document.createElement("button");
deleteTask.style.cssText = 'height: 30px; width: 60px;';
deleteTask.innerText = 'Delete';
newTask.appendChild(text);
deleteTask.appendChild(newTask);
document.getElementById("taskLister").appendChild(newTask);
}
Firstable the <input> HTML element has no closing tag and you have misspelled the closing tag name </button>
function taskList() {
let item = document.getElementById("taskInput").value;
let text = document.createTextNode(item);
let newTask = document.createElement("li");
let deleteTask = document.createElement("button");
deleteTask.style.cssText = 'height: 30px; width: 60px;';
deleteTask.innerText = 'Delete';
newTask.appendChild(text);
deleteTask.appendChild(newTask);
document.getElementById("taskLister").appendChild(newTask);
}
<div class="container">
<h1>TO DO LIST</h1>
<form id="taskForm">
<input id="taskInput">
<button type="button" id="taskButton" onclick="taskList()">Click Here</button>
</form>
</div>
<div>
<ul id="taskLister"></ul>
</div>
I thought you want to add a remove button to each list item so here is an example
function taskList() {
// using inner HTML is much clear and gives a cleaner code
document.getElementById("taskLister").innerHTML += `
<li>${document.querySelector("#taskInput").value}<button onclick="this.parentElement.remove()">×</button></li>
`;
}
<div class="container">
<h1>TO DO LIST</h1>
<form id="taskForm">
<input id="taskInput">
<button type="button" id="taskButton" onclick="taskList()">Click Here</button>
</form>
</div>
<div>
<ul id="taskLister"></ul>
</div>

Show/Hide Div as Overlay

I am trying to create image overlays which can toggle on and off by clicking a button. Basically I have one main image then I want to click button A and have overlay A show up over the main image and click button B and have overlay A go away and show overlay B.
Currently I am trying to do this by creating a hidden div which has a background image on it. The current code works for the first button listed but not for any of the others.
<div class="hide schoolContent" id="schools"
</div>
<div class ="hide recreationContent" id="recreation">
</div>
<div class="hide restaurantsContent"id="restaurants">
</div>
<div class="hide banksContent" id="banks">
</div>
<div class="hide groceriesContent"id="groceries">
</div>
<div class="hide transportationContent"id="transportation">
</div>
<div class="hide libraryContent" id="library"></div>
<div>
<button class="alertName" name="schoolContent">Schools</button>
<button class="alertName" name="recreationContent">Recreation</button>
<button class="alertName" name="restaurantsContent">Restaurants</button>
<button class="alertName" name="banksContent">Banks</button>
<button class="alertName" name="groceriesContent">Groceries</button>
<button class="alertName" name="transportationContent">Study Transportation</button>
<button class="alertName" name="libraryContent">Library</button>
</div>
<script>var alertName = document.getElementsByClassName("alertName");
var myFunction = function() {
var hide = document.getElementsByClassName("hide");
for (var i =< 0; i < hide.length; i++) {
hide[i].style.display = "none";
}
var name = this.getAttribute("name");
var show = document.querySelector('.' + name);
if (show.style.display = "none") {
show.style.display = "block";
}
else {
show.style.display = "none";
}
};
for (var i = 0; i < alertName.length; i++) {
alertName[i].addEventListener('click', myFunction);
}</script>

Categories

Resources