Why javascript 'if else' statement seems looping over - javascript

I am writing some javascript code called account register. The requirement is showing information inputted on the screen when clicked the register button, and each row can be deleted by clicking the delete button on the left.
My problem is when the first time I click the register button, information not showing up. The second time is fine. From the third time, extra rows start added. For me it seems the 'if else' statement is looping over inside the function.
What is the reason of that?
Execute result
var counterVal = 0;
document.getElementById("tuikaBtn").onclick = function() {
const addButton = document.getElementById('tuikaBtn');
const listContainer = document.getElementById('result');
const name = document.getElementById('namae');
const nick = document.getElementById('nickname');
const rmvButton = document.getElementById('rmv');
console.log('counter = ' + counterVal);
if (name.value == "" | nick.value == "") {
window.alert("Please input both name and nickname.");
} else if (counterVal == 3) {
document.getElementById("tuikaBtn").style.display = 'none';
} else {
//funtion to get parent item
const handleRemove = function(e) {
const item = e.target.closest('.item');
//remove the listener, to avoid memory leaks.
item.querySelector('.remove-btn').removeEventListener('click', handleRemove);
item.parentElement.removeChild(item);
};
//adds text and button to list once clicked the button
addButton.addEventListener('click', e => {
const item = document.createElement('div');
const paragraph = document.createElement('div');
const remove = document.createElement('button');
item.classList.add('item');
paragraph.classList.add('paragraph-style');
remove.classList.add('remove-btn');
paragraph.textContent = name.value + ' ' + nick.value;
remove.textContent = 'Remove';
item.append(paragraph);
item.append(remove);
listContainer.append(item);
name.value = '';
nick.value = '';
remove.addEventListener('click', handleRemove);
})
return counterVal += 1;
}
}
.base {
margin: 2% 7% 0;
height: 500px;
background: blue;
padding: 5% 10%;
box-shadow: 5px 9px 8px 5px rgba(0, 0, 0, 0.5);
}
input {
width: 300px;
height: 40px;
font-size: large;
}
#tuikaBtn {
background: green;
}
h1 {
font-family: serif;
}
.form-control::placeholder {
color: #cacaca;
opacity: 1;
}
table {
border-collapse: collapse;
}
th,
td {
border: 1px solid #312929;
padding: 5px 10px;
}
.card {
width: 100%;
height: 350px;
}
.back {
padding: 30px;
position: absolute;
bottom: 0;
right: 0;
}
.form-group {
margin: 10px 0 15px 0px;
}
#result {
font-size: 120%;
margin: 10;
margin: 10px 20px;
padding: 10px 5px 20px;
margin: 10px 5px 10px 5px;
}
.row .card {
color: black;
}
.card {
color: blue;
display: block;
position: relative;
}
#modal {
display: none;
margin: 1.5em auto 0;
background-color: white;
border: 1px solid black;
width: 50%;
padding: 10px 20px;
position: fixed;
border-radius: 5px;
}
#overLay {
display: none;
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 120%;
background-color: rgba(0, 0, 0, 0.75);
}
.items {
display: flex;
}
.item {
display: grid;
grid-auto-flow: column;
grid-template-columns: 1fr 6em;
grid-column-gap: 1em;
margin-bottom: 0.667em;
align-items: center;
}
.paragraph-style {
font-style: italic;
}
<div class="base container">
<div class="row">
<h1>Account Register</h1>
</div>
<div class="row">
<div class="card" id="card">
<div class="card-block">
<form id="form-area" class="form-inline" method="post">
<div class="form-group">
<div class="input-group">
<input id="namae" name="namae" type="text" class="form-control" placeholder="Full Name">
</div>
</div>
<div class="form-group">
<div class="input-group">
<input id="nickname" name="nickname" type="text" class="form-control" placeholder="Nick Name">
</div>
</div>
<div class="form-group">
<input id="tuikaBtn" type="button" name="touroku" value="Add">
</div>
</form>
<div id="tuikaMoto">User Information</div>
<div id="result"></div>
</div>
</div>
</div>
</div>
<div id="overLay"></div>

Only one tuikaBtn.onclick is needed. Also no need of counter
document.getElementById("tuikaBtn").onclick = function() {
const listContainer = document.getElementById('result');
const name = document.getElementById('namae');
const nick = document.getElementById('nickname');
const rmvButton = document.getElementById('rmv');
if (name.value == "" || nick.value == "") {
window.alert("Please input both name and nickname.");
}
else {
//funtion to get parent item
const handleRemove = function(e) {
const item = e.target.closest('.item');
//remove the listener, to avoid memory leaks.
item.querySelector('.remove-btn').removeEventListener('click', handleRemove);
item.parentElement.removeChild(item);
document.getElementById("tuikaBtn").style.display = '';
};
//adds text and button to list once clicked the button
////// addButton.addEventListener('click', e => { /// // /no need of this
const item = document.createElement('div');
const paragraph = document.createElement('div');
const remove = document.createElement('button');
item.classList.add('item');
paragraph.classList.add('paragraph-style');
remove.classList.add('remove-btn');
paragraph.textContent = name.value + ' ' + nick.value;
remove.textContent = 'Remove';
item.append(paragraph);
item.append(remove);
listContainer.append(item);
name.value = '';
nick.value = '';
remove.addEventListener('click', handleRemove);
if(listContainer.querySelectorAll('.item').length>=3)
{
document.getElementById("tuikaBtn").style.display = 'none';
}else{
document.getElementById("tuikaBtn").style.display = '';
}
////// })
}
}
.base {
margin: 2% 7% 0;
height: 500px;
background: blue;
padding: 5% 10%;
box-shadow: 5px 9px 8px 5px rgba(0, 0, 0, 0.5);
}
input {
width: 300px;
height: 40px;
font-size: large;
}
#tuikaBtn {
background: green;
}
h1 {
font-family: serif;
}
.form-control::placeholder {
color: #cacaca;
opacity: 1;
}
table {
border-collapse: collapse;
}
th,
td {
border: 1px solid #312929;
padding: 5px 10px;
}
.card {
width: 100%;
height: 350px;
}
.back {
padding: 30px;
position: absolute;
bottom: 0;
right: 0;
}
.form-group {
margin: 10px 0 15px 0px;
}
#result {
font-size: 120%;
margin: 10;
margin: 10px 20px;
padding: 10px 5px 20px;
margin: 10px 5px 10px 5px;
}
.row .card {
color: black;
}
.card {
color: blue;
display: block;
position: relative;
}
#modal {
display: none;
margin: 1.5em auto 0;
background-color: white;
border: 1px solid black;
width: 50%;
padding: 10px 20px;
position: fixed;
border-radius: 5px;
}
#overLay {
display: none;
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 120%;
background-color: rgba(0, 0, 0, 0.75);
}
.items {
display: flex;
}
.item {
display: grid;
grid-auto-flow: column;
grid-template-columns: 1fr 6em;
grid-column-gap: 1em;
margin-bottom: 0.667em;
align-items: center;
}
.paragraph-style {
font-style: italic;
}
<div class="base container">
<div class="row">
<h1>Account Register</h1>
</div>
<div class="row">
<div class="card" id="card">
<div class="card-block">
<form id="form-area" class="form-inline" method="post">
<div class="form-group">
<div class="input-group">
<input id="namae" name="namae" type="text" class="form-control" placeholder="Full Name">
</div>
</div>
<div class="form-group">
<div class="input-group">
<input id="nickname" name="nickname" type="text" class="form-control" placeholder="Nick Name">
</div>
</div>
<div class="form-group">
<input id="tuikaBtn" type="button" name="touroku" value="Add">
</div>
</form>
<div id="tuikaMoto">User Information</div>
<div id="result"></div>
</div>
</div>
</div>
</div>
<div id="overLay"></div>

Related

How would I toggle an object property between true and false?

let myLibrary = [
{
id: 0,
title: "The Once and Future King",
author: "White",
pages: 654,
read: false,
},
{
id: 1,
title: "The Hobbit",
author: "Tolkien",
pages: 304,
read: false,
},
];
const bookContent = document.getElementById("content");
function displayBook(book) {
const addBook = document.createElement("div");
addBook.className = "book";
addBook.id = book.id;
bookContent.appendChild(addBook);
addBook.innerHTML = `
<div class="title">
<p class="bookTitle">
<span>${book.title}</span>
</p>
</div>
<div class="body">
<p>
Author: <span>${book.author}</span>
</p>
<p>
Pages: <span>${book.pages}</span>
</p>
</div>
<div class="read">
<label class="switch" data-book="0">
<input type="checkbox" />
<span class="slider round"></span>
</label>
</div>
<div class="delete">
<button class="delete-btn">DELETE</button>
</div>`;
}
// Display your original object list
myLibrary.forEach((book) => {
displayBook(book);
});
// Handle your object creation
const form = document.getElementById("form");
form.addEventListener("submit", updateLibrary);
function updateLibrary(event) {
// Need this so it doesn't refresh page
event.preventDefault();
const title = document.getElementById("title").value;
const author = document.getElementById("author").value;
const pages = document.getElementById("pages").value;
const book = {
title: title,
author: author,
pages: parseInt(pages),
read: false,
};
// Adds object to array
myLibrary.push(book);
// Displays new book
displayBook(book);
// Reset form
resetForm();
// Close form
document.getElementById("addBookForm").style.display = "none";
console.log(myLibrary);
}
// Resets the form so user can input another book
function resetForm() {
document.getElementById("form").reset();
}
// The form is automatically set to hidden. This loads it up for the user
const openForm = function () {
document.getElementById("addBookForm").style.display = "block";
document.getElementById("title").focus();
};
// Sets the form display back to none
const closeForm = () =>
(document.getElementById("addBookForm").style.display = "none");
/* .main {
} */
.header {
display: flex;
flex-direction: column;
background-color: #c689c6;
height: 150px;
border: 1px solid #3b133b;
}
.btn {
margin: 0 auto;
margin-top: 55px;
display: block;
text-align: center;
background-color: #4649ff;
padding: 0.75rem 1.25rem;
border-radius: 10rem;
color: #fff;
cursor: pointer;
font-size: 1rem;
letter-spacing: 0.15rem;
transition: all 0.3s;
}
.btn:hover {
background-color: #3134fa;
}
.content {
display: flex;
flex-flow: row wrap;
align-content: flex-start;
justify-content: flex-start;
background-color: #fffdfa;
height: auto;
}
.book {
border: 2px solid #ffa94d;
background-color: #ffd8a8;
color: #d9480f;
width: 280px;
height: 365px;
margin: 10px;
}
.title {
border-bottom: 2px solid #ffa94d;
}
.title p {
display: flex;
align-items: center;
text-align: center;
justify-content: center;
font-size: larger;
}
.title span {
color: #3c4048;
}
.body {
border: 1px solid transparent;
height: 200px;
background-color: #fff4e6;
}
.body p {
padding-left: 20px;
}
p span {
color: #3c4048;
}
.read {
display: flex;
align-items: center;
justify-content: center;
height: 50px;
border-top: 2px solid #ffa94d;
text-align: center;
}
/* The switch - the box around the slider */
.switch {
position: relative;
display: inline-block;
width: 60px;
height: 34px;
}
/* Hide default HTML checkbox */
.switch input {
opacity: 0;
width: 0;
height: 0;
}
/* The slider */
.slider {
position: absolute;
cursor: pointer;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: #ccc;
-webkit-transition: 0.4s;
transition: 0.4s;
}
.slider:before {
position: absolute;
content: "";
height: 26px;
width: 26px;
left: 4px;
bottom: 4px;
background-color: white;
-webkit-transition: 0.4s;
transition: 0.4s;
}
input:checked + .slider {
background-color: #3d8361;
}
input:focus + .slider {
box-shadow: 0 0 1px #3d8361;
}
input:checked + .slider:before {
-webkit-transform: translateX(26px);
-ms-transform: translateX(26px);
transform: translateX(26px);
}
/* Rounded sliders */
.slider.round {
border-radius: 34px;
}
.slider.round:before {
border-radius: 50%;
}
.delete {
height: 50px;
border-top: 2px solid #ffa94d;
}
.delete-btn {
margin: 0 auto;
margin-top: 8px;
display: block;
text-align: center;
background-color: #e94560;
padding: 0.5rem 0.75rem;
border-radius: 10rem;
color: #fff;
cursor: pointer;
letter-spacing: 0.15rem;
transition: all 0.3s;
}
.delete-btn:hover {
background-color: #e7082d;
}
.close-btn {
color: #e7082d;
font-size: large;
background-color: #c689c6;
border: none;
float: right;
cursor: pointer;
}
/* THE FORM */
.form-content {
display: flex;
justify-content: center;
}
.form {
display: none;
position: fixed;
margin-top: 5px;
border: 2px solid #3b133b;
animation: openForm 0.5s;
z-index: 1;
}
#keyframes openForm {
from {
transform: scale(0);
}
to {
transform: scale(1);
}
}
.form h1 {
text-align: center;
}
.form-container {
background-color: #c689c6;
border: 2px solid black;
max-width: 300px;
padding: 10px;
}
.form-container h1 {
padding-left: 20px;
}
.form-container input[type="text"],
.form-container input[type="number"] {
width: 80%;
padding: 15px;
margin: 5px 0 22px 0;
border: none;
}
.form-container input[type="text"]:focus,
.form-container input[type="number"]:focus {
outline: none;
}
<!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" />
<title>Library</title>
</head>
<body>
<div class="main">
<div class="header">
<button class="btn" id="btn" onclick="openForm()">Add a Book</button>
</div>
<div class="form-content">
<div class="form" id="addBookForm">
<form id="form" action="" class="form-container">
<button type="button" class="close-btn" onclick="closeForm()">
x
</button>
<h1>Add a Book</h1>
<label for="title">Title</label>
<input
type="text"
placeholder="Title"
name="title"
id="title"
required
/>
<label for="author">Author</label>
<input
type="text"
placeholder="Author"
name="author"
id="author"
required
/>
<label for="pages">Pages</label>
<input
type="number"
placeholder="Pages"
name="pages"
required
id="pages"
/>
<button type="submit" id="submit-btn">Submit</button>
</form>
</div>
</div>
<div id="content" class="content"></div>
</div>
</body>
</html>
I have a form where the user inputs information from a book they are reading and upon hitting submit, the information is sent as its own object inside an array. I also have a forEach method running which loops through the array and displays each object as a div on the web page.
let myLibrary = [];
const book = {
title: title,
author: author,
pages: parseInt(pages),
read: false,
};
myLibrary.push(book)
As you can see from the code above, the three properties that the user fills out are the books title, author and page count. There's also a property that is automatically added called the read property and it is automatically set as false.
The Problem
My problem is this. I have the following code displayed at the bottom of each div.
<div class="read">
<label class="switch">
<input type="checkbox" />
<span class="slider round"></span>
</label>
</div>
This code is very simple. It's a toggle switch which I found here.
I want it so when the toggle switch is grayed out, the read status is set to false. But when the toggle switch is turned on, the read property is set to true. I am having a very difficult time figuring out how to get this done.
What I've Tried
I was able to use an onclick to select the toggle switch's parent element, and I tested it using console.log however I am unsure of where to go from there. I attempted to update the book.read to true using the ternary operator but it was out of scope and resulted in an error.
document.querySelector(".main").onclick = (ev) => {
let el = ev.target.classList.contains("switch")
? ev.target.parentElement
: ev.target.classList.contains("slider")
? ev.target
: false;
if (el) {
let toggle = el.parentElement.parentElement.parentElement;
let index = [...toggle.parentElement.children].indexOf(toggle);
myLibrary[index].read = false ? false : true;
console.log(myLibrary[index].read);
}
console.log(myLibrary);
};
Change this
function displayBook(book) {
...
<label class="switch" data-book="0">
to
function displayBook(book,bookIndex) {
...
<label class="switch" data-book="${bookIndex}">
and
myLibrary.forEach((book) => {
displayBook(book);
});
to
myLibrary.forEach((book,i) => {
displayBook(book,i);
});
lastly change
// Displays new book
displayBook(book);
to
// Displays new book
displayBook(book,myLibrary.length-1);
Here is the code inclusive a delete function
It would be slightly simpler if we had an associate array on book_id
Note I removed the numeric ID because it is not needed since the index of the array is the same
let myLibrary = [{
title: "The Once and Future King",
author: "White",
pages: 654,
read: false,
},
{
title: "The Hobbit",
author: "Tolkien",
pages: 304,
read: false,
},
];
const bookContent = document.getElementById("content");
const formDiv = document.getElementById("addBookForm");
function displayBook(book, idx) {
const addBook = document.createElement("div");
addBook.className = "book";
addBook.id = `book_${idx}`;
bookContent.appendChild(addBook);
addBook.innerHTML = `
<div class="title">
<p class="bookTitle">
<span>${book.title}</span>
</p>
</div>
<div class="body">
<p>
Author: <span>${book.author}</span>
</p>
<p>
Pages: <span>${book.pages}</span>
</p>
</div>
<div class="read">
<label class="switch" data-book="${idx}">
<input type="checkbox" />
<span class="slider round"></span>
</label>
</div>
<div class="delete">
<button class="delete-btn">DELETE</button>
</div>`;
}
// Display your original object list
myLibrary.forEach((book, i) => {
displayBook(book, i);
});
const deleteBook = (e) => {
const parent = e.target.closest("div.book");
const idx = parent.querySelector(".switch").dataset.book;
parent.remove();
console.log(idx);
myLibrary.splice(idx, 1);
console.log(myLibrary);
content.querySelectorAll("div.book").forEach((book, i) => { // reset the hard way
book.id = `book_${i}`;
book.querySelector("label.switch").dataset.book = i;
})
};
content.addEventListener("click", function(e) {
const tgt = e.target;
if (!tgt.matches(".delete-btn")) return; // not the delete
deleteBook(e); // pass the event to the delete
})
// Handle your object creation
const form = document.getElementById("form");
form.addEventListener("submit", updateLibrary);
function updateLibrary(event) {
// Need this so it doesn't refresh page
event.preventDefault();
const title = document.getElementById("title").value;
const author = document.getElementById("author").value;
const pages = document.getElementById("pages").value;
const book = {
title: title,
author: author,
pages: parseInt(pages),
read: false,
};
// Adds object to array
myLibrary.push(book);
// Displays new book
displayBook(book);
// Reset form
resetForm();
// Close form
formDiv.style.display = "none";
console.log(myLibrary);
}
// Resets the form so user can input another book
function resetForm() {
document.getElementById("form").reset();
}
// The form is automatically set to hidden. This loads it up for the user
const openForm = function() {
formDiv.style.display = "block";
document.getElementById("title").focus();
};
// Sets the form display back to none
const closeForm = () => formDiv.style.display = "none";
/* .main {
} */
.header {
display: flex;
flex-direction: column;
background-color: #c689c6;
height: 150px;
border: 1px solid #3b133b;
}
.btn {
margin: 0 auto;
margin-top: 55px;
display: block;
text-align: center;
background-color: #4649ff;
padding: 0.75rem 1.25rem;
border-radius: 10rem;
color: #fff;
cursor: pointer;
font-size: 1rem;
letter-spacing: 0.15rem;
transition: all 0.3s;
}
.btn:hover {
background-color: #3134fa;
}
.content {
display: flex;
flex-flow: row wrap;
align-content: flex-start;
justify-content: flex-start;
background-color: #fffdfa;
height: auto;
}
.book {
border: 2px solid #ffa94d;
background-color: #ffd8a8;
color: #d9480f;
width: 280px;
height: 365px;
margin: 10px;
}
.title {
border-bottom: 2px solid #ffa94d;
}
.title p {
display: flex;
align-items: center;
text-align: center;
justify-content: center;
font-size: larger;
}
.title span {
color: #3c4048;
}
.body {
border: 1px solid transparent;
height: 200px;
background-color: #fff4e6;
}
.body p {
padding-left: 20px;
}
p span {
color: #3c4048;
}
.read {
display: flex;
align-items: center;
justify-content: center;
height: 50px;
border-top: 2px solid #ffa94d;
text-align: center;
}
/* The switch - the box around the slider */
.switch {
position: relative;
display: inline-block;
width: 60px;
height: 34px;
}
/* Hide default HTML checkbox */
.switch input {
opacity: 0;
width: 0;
height: 0;
}
/* The slider */
.slider {
position: absolute;
cursor: pointer;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: #ccc;
-webkit-transition: 0.4s;
transition: 0.4s;
}
.slider:before {
position: absolute;
content: "";
height: 26px;
width: 26px;
left: 4px;
bottom: 4px;
background-color: white;
-webkit-transition: 0.4s;
transition: 0.4s;
}
input:checked+.slider {
background-color: #3d8361;
}
input:focus+.slider {
box-shadow: 0 0 1px #3d8361;
}
input:checked+.slider:before {
-webkit-transform: translateX(26px);
-ms-transform: translateX(26px);
transform: translateX(26px);
}
/* Rounded sliders */
.slider.round {
border-radius: 34px;
}
.slider.round:before {
border-radius: 50%;
}
.delete {
height: 50px;
border-top: 2px solid #ffa94d;
}
.delete-btn {
margin: 0 auto;
margin-top: 8px;
display: block;
text-align: center;
background-color: #e94560;
padding: 0.5rem 0.75rem;
border-radius: 10rem;
color: #fff;
cursor: pointer;
letter-spacing: 0.15rem;
transition: all 0.3s;
}
.delete-btn:hover {
background-color: #e7082d;
}
.close-btn {
color: #e7082d;
font-size: large;
background-color: #c689c6;
border: none;
float: right;
cursor: pointer;
}
/* THE FORM */
.form-content {
display: flex;
justify-content: center;
}
.form {
display: none;
position: fixed;
margin-top: 5px;
border: 2px solid #3b133b;
animation: openForm 0.5s;
z-index: 1;
}
#keyframes openForm {
from {
transform: scale(0);
}
to {
transform: scale(1);
}
}
.form h1 {
text-align: center;
}
.form-container {
background-color: #c689c6;
border: 2px solid black;
max-width: 300px;
padding: 10px;
}
.form-container h1 {
padding-left: 20px;
}
.form-container input[type="text"],
.form-container input[type="number"] {
width: 80%;
padding: 15px;
margin: 5px 0 22px 0;
border: none;
}
.form-container input[type="text"]:focus,
.form-container input[type="number"]:focus {
outline: none;
}
<div class="main">
<div class="header">
<button class="btn" id="btn" onclick="openForm()">Add a Book</button>
</div>
<div class="form-content">
<div class="form" id="addBookForm">
<form id="form" action="" class="form-container">
<button type="button" class="close-btn" onclick="closeForm()">
x
</button>
<h1>Add a Book</h1>
<label for="title">Title</label>
<input type="text" placeholder="Title" name="title" id="title" required />
<label for="author">Author</label>
<input type="text" placeholder="Author" name="author" id="author" required />
<label for="pages">Pages</label>
<input type="number" placeholder="Pages" name="pages" required id="pages" />
<button type="submit" id="submit-btn">Submit</button>
</form>
</div>
</div>
<div id="content" class="content"></div>
</div>

Strange behavior while adding DOM element using addEventListener() on a button

I'm trying to create a project card with user info when the user clicks on a button. When the user clicks the new project button, a modal form pops up that takes the user info and has a create button. The program should add a new project card whenever the user clicks the create button. To achieve this I added a click event listener to the Add new project button and another to Create button. I nested the create event listener inside the add new project event listener.
Here's the event listener.
addTileBtn.addEventListener("click", (e) => {
e.preventDefault();
modal.style.display = "block";
const titleField = document.querySelector("#title");
const descriptionField = document.querySelector("#description");
const create = document.querySelector("#create");
const close = document.querySelector("#close");
create.addEventListener("click", (e) => {
e.preventDefault();
title = titleField.value;
description = descriptionField.value;
function createProjectTile() {
const projectTile = document.createElement("div");
projectTile.classList.add("cards-grid__tile");
projectTile.textContent = title;
console.log(title, description);
return projectTile;
}
cardsGrid.appendChild(createProjectTile());
modal.style.display = "none";
});
close.addEventListener("click", (e) => {
e.preventDefault();
modal.style.display = "none";
});
});
The problem is that when I create the first card it works fine. But the second time, it creates two cards and 3 cards on the 3rd time and so on.
Here is the JSFiddle link for the full code.
I've edited your code, this should be what you wanted:
const logoutBtn = document.querySelector("#logout");
const addTileBtn = document.querySelector("#add-tile");
const cardsGrid = document.querySelector(".cards-grid");
const modal = document.querySelector(".modal");
const titleField = document.querySelector("#title");
const descriptionField = document.querySelector("#description");
const create = document.querySelector("#create");
const close = document.querySelector("#close");
addTileBtn.addEventListener("click", (e) => {
e.preventDefault();
modal.style.display = "block";
titleField.value = "";
descriptionField.value = "";
});
create.addEventListener("click", (e) => {
e.preventDefault();
title = titleField.value;
description = descriptionField.value;
function createProjectTile() {
const projectTile = document.createElement("div");
projectTile.classList.add("cards-grid__tile");
projectTile.textContent = title;
console.log(title, description);
return projectTile;
}
cardsGrid.appendChild(createProjectTile());
modal.style.display = "none";
});
close.addEventListener("click", (e) => {
e.preventDefault();
modal.style.display = "none";
});
:root {
--main-red: #be3144;
--main-white: #f0f0f0;
--main-gray: #303841;
--main-blue: #45567d;
--main-blue3: #1c262f;
--main-blue2: #27333d;
--main-blue1: #2e3d49;
--main-light-blue: #02b3e4;
--main-black: #000000;
--main-light-black: #3a3d40;
--main-dark-black: #181719;
}
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
html,
body {
height: 100%;
}
img {
display: block;
max-width: 100%;
height: auto;
}
body {
font-family: "Poppins", sans-serif;
font-size: 1.8rem;
font-weight: 400;
line-height: 1.4;
color: var(--main-white);
}
h1,
h2 {
font-family: "Raleway", sans-serif;
font-weight: 700;
text-align: center;
}
h1 {
font-size: 3.5rem;
}
h2 {
font-size: 2rem;
color: var(--main-blue);
display: block;
}
p {
font-size: 1.8rem;
font-weight: 200;
font-style: italic;
color: var(--main-white);
}
a {
text-decoration: none;
text-align: center;
display: block;
}
.main {
display: flex;
flex-direction: row;
justify-content: space-between;
height: 100vh;
background-color: var(--main-white);
}
.box {
border: none;
box-shadow: 0 2px 4px rgb(0 0 0 / 10%), 0 8px 16px rgb(0 0 0 / 10%);
border-radius: 8px;
background-color: #fff;
}
.box__fields {
padding: 20px;
}
.box-field {
margin-bottom: 20px;
display: flex;
justify-content: center;
}
.icon {
position: absolute;
padding: 10px;
color: gray;
min-width: 50px;
text-align: center;
font-size: 20px;
top: 50%;
transform: translateY(-50%);
}
input,
textarea {
font-size: 17px;
padding: 14px 16px;
width: 300px;
cursor: text;
border: 1px solid var(--main-gray);
border-radius: 6px;
outline: none;
padding-left: 45px;
}
.box-btn {
border: none;
border-radius: 6px;
font-size: 20px;
line-height: 48px;
padding: 0 16px;
}
.app,
.main-content {
height: 100%;
}
.title-area {
background-color: var(--main-blue3);
width: 100%;
font-size: 18px;
min-height: 60px;
display: flex;
flex-direction: row;
flex-wrap: wrap;
justify-content: space-between;
align-items: center;
position: fixed;
top: 0;
left: 0;
}
.title-area__item {
padding: 10px 30px;
}
.logout-btn {
border: none;
border-radius: 6px;
font-size: 20px;
line-height: 30px;
padding: 0 16px;
width: 100px;
cursor: pointer;
color: #fff;
background-color: var(--main-light-blue);
}
.logout-btn:hover {
background-color: #029be4;
}
.content-area {
margin-top: 60px;
width: 100%;
height: 100%;
overflow: auto;
background-color: var(--main-blue);
}
.cards-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
grid-gap: 50px;
margin-bottom: 3rem;
padding: 5rem 3rem;
}
.cards-grid__tile {
background-color: var(--main-blue2);
max-width: 200px;
padding: 30px;
text-align: center;
font-size: 1.2rem;
}
.add-tile-btn {
border: none;
border-radius: 6px;
font-size: 15px;
line-height: 48px;
padding: 0 10px;
cursor: pointer;
color: #fff;
background-color: var(--main-light-blue);
}
.modal {
display: none;
width: 350px;
font-size: 1.2rem;
position: relative;
top: 10%;
left: 50%;
transform: translateX(-50%);
overflow: visible;
}
.box {
background-color: var(--main-blue1);
opacity: 0.95;
}
.box-field {
flex-direction: column;
}
input,
textarea {
padding: 5px 10px;
resize: none;
}
.wrapper {
position: relative;
text-align: center;
}
.create-btn {
width: 100px;
cursor: pointer;
color: #fff;
background-color: var(--main-light-blue);
}
.close {
cursor: pointer;
position: absolute;
top: 20px;
left: 290px;
}
#modal-form {
position: absolute;
}
.icon {
color: var(--main-blue3);
}
<div class="app">
<div class="nav-wrapper">
<nav id="nav" class="nav"></nav>
</div>
<div class="main-content">
<div class="title-area">
<div class="title-area__item">Menu</div>
<div class="title-area__item">Boards</div>
<div class="title-area__item">
<button id="logout" class="logout-btn btn">
Logout
</button>
</div>
</div>
<div class="content-area">
<div class="modal">
<form id="modal-form" class="box">
<a id="close" class="close">
<i class="fa fa-times icon">close</i>
</a>
<div class="box__fields">
<div class="box-field">
<label for="title"> Title </label>
<input
id="title"
type="text"
name="title"
required
autofocus
/>
</div>
<div class="box-field">
<label for="description">
Description
</label>
<textarea
id="description"
name="title"
rows="6"
cols="40"
></textarea>
</div>
<div class="box-field">
<div class="wrapper">
<button
id="create"
class="create-btn box-btn btn"
>
Create
</button>
</div>
</div>
</div>
</form>
</div>
<div class="cards-grid">
<div class="cards-grid__tile">
<button id="add-tile" class="add-tile-btn btn">
+ Add new project
</button>
</div>
</div>
</div>
</div>
</div>

Form is not taking values ​from querySelector

I have a "piggy bank" project that saves and withdraws an amount of money passed through two different forms (Each modal is for one type of transaction), but when trying to withdraw, the values ​​are empty as in the example:
{date: "", amount: "", type: "Retirada"}
When saving the values ​​normally:
{date: "2021-02-27", amount: "1", type: "Depósito"}
I'm not able to find the error of not taking the values
Snipped Code:
const Modals = {
modalType: "",
openModals(type){
if(type == "Depósito") {
this.modalType = type;
document.querySelector('.modal1-overlay').classList.add('active')
} else {
document.querySelector('.modal2-overlay').classList.add('active')
this.modalType = type;
}
},
closeModals(type) {
if(type == "Depósito") {
document.querySelector('.modal1-overlay').classList.remove('active')
this.modalType = "";
} else {
document.querySelector('.modal2-overlay').classList.remove('active')
this.modalType = "";
}
},
openErrorModal(message) {
document.querySelector('.modalError-overlay').classList.add('active')
document.getElementById('errorMessage').innerHTML = message
},
closeErrorModal() {
document.querySelector('.modalError-overlay').classList.remove('active')
}
}
const Transaction = {
all: [],
add(transaction) {
Transaction.all.push(transaction)
App.reload()
},
totalBalance() {
let total = 0;
Transaction.all.forEach(transaction => {
if (transaction.type == "Retirada") {
total -= transaction.amount;
} else {
total += transaction.amount;
}
})
return total;
},
}
const DOM = {
transactionsContainer: document.querySelector('#data-table tbody'),
addTransaction(transaction, index) {
const tr = document.createElement('tr');
tr.innerHTML = this.innerHTMLTransaction(transaction);
this.transactionsContainer.appendChild(tr)
},
innerHTMLTransaction(transaction) {
const CSSclass = transaction.type === 'Retirada' ? "withdraw" : "income"
const amount = Utils.formatCurrency(transaction.amount, transaction.type)
const html = `
<tr>
<td class="${CSSclass}">${transaction.type}</td>
<td class="price-transaction">${amount}</td>
<td class="date">${transaction.date}</td>
<td></td>
</tr>
`;
return html;
},
updateBalance() {
document
.getElementById("totalCurrency")
.innerHTML = Utils.formatCurrency(Transaction.totalBalance())
},
clearTransactions() {
DOM.transactionsContainer.innerHTML = "";
}
}
const Utils = {
formatAmount(value) {
value = Number(value)*100
return value;
},
formatDate(date){
const splittedDate = date.split("-")
return `${splittedDate[2]}/${splittedDate[1]}/${splittedDate[0]}`
},
formatCurrency(value, type) {
if (type == "Retirada") {
value = String(value).replace(/\D/g, "");
value = Number(value) / 100
value = value.toLocaleString("pt-BR", {style: "currency", currency: "BRL"})
return "- " + value;
} else {
const signal = "";
value = String(value).replace(/\D/g, "");
value = Number(value) / 100
value = value.toLocaleString("pt-BR", {style: "currency", currency: "BRL"})
return value
}
}
}
const Form = {
amount: Modals.modalType == "Retirada" ? document.querySelector('input#amount2') : document.querySelector('input#amount'),
date: Modals.modalType == "Retirada" ? document.querySelector('input#date2') : document.querySelector('input#date'),
getValues() {
return {
date: this.date.value,
amount: this.amount.value,
type: Modals.modalType
}
},
validateField() {
const {date, amount, type} = Form.getValues()
if(date.trim() === "" || amount.trim() === "" || type.trim() === "") {
throw new Error("Por favor, preencha todos os campos!")
}
},
formatValues() {
let { date, amount, type} = Form.getValues()
amount = Utils.formatAmount(amount)
date = Utils.formatDate(date)
return {date, amount, type}
},
clearFieldsForm(){
Form.amount.value = "";
Form.date.value = "";
Modals.modalType = "";
},
submit(event) {
event.preventDefault()
try {
console.log(this.getValues())
// Form.validateField()
const transaction = Form.formatValues()
Transaction.add(transaction)
Modals.closeModals(Modals.modalType)
Form.clearFieldsForm();
} catch (error) {
Modals.openErrorModal(error.message)
}
}
}
const App = {
init() {
Transaction.all.forEach(transaction => {
DOM.addTransaction(transaction)
});
DOM.updateBalance()
},
reload() {
DOM.clearTransactions()
App.init()
}
}
App.init()
/* Global CSS */
* {
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: 'Ubuntu', sans-serif;
}
:root {
--darkblue: #363f5f;
--green: rgb(0, 172, 0);
}
body {
background-color: rgb(241, 241, 241);
}
.sr-only {
position: absolute;
margin: 0;
width: 1px;
height: 1px;
padding: 0;
margin: -1px;
overflow: hidden;
clip: rect(0,0,0,0);
white-space: nowrap;
border-width: 0;
}
.container {
width: min(90vw, 800px);
margin: auto;
}
/* Header */
header {
background-color: green;
padding: 2rem 2rem 5rem 2rem;
text-align: center;
color: white;
}
/* Modal CSS */
.modal1-overlay {
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.7);
position: fixed;
top: 0;
display: flex;
align-items: center;
justify-content: center;
opacity: 0;
visibility: hidden;
}
.modal1-overlay.active {
opacity: 1;
visibility: visible;
}
.modal1 {
background:snow;
padding: 2.4rem;
position: relative;
display: flex;
flex-direction: column;
}
.modal2-overlay {
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.7);
position: fixed;
top: 0;
display: flex;
align-items: center;
justify-content: center;
opacity: 0;
visibility: hidden;
}
.modal2-overlay.active {
opacity: 1;
visibility: visible;
}
.modal2 {
background:snow;
border-radius: 2px;
padding: 2.4rem;
position: relative;
}
#form {
max-width: 500px;
}
#form h2 {
margin-top: 0;
}
.modalError-overlay {
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.7);
position: fixed;
top: 0;
display: flex;
align-items: center;
justify-content: center;
opacity: 0;
visibility: hidden;
}
.modalError-overlay.active {
opacity: 1;
transition: opacity .25s ease-in;
visibility: visible;
}
.modalErrorContainer {
background-color: white;
border-radius: 2px;
width: 70vh;
height: 16vh;
padding: 10px;
}
.modalErrorContainer h3 {
margin-bottom: 1.5rem;
}
input {
border: 1px solid rgba(0, 0, 0, 0.192);
border-radius: 0.2rem;
padding: 0.8rem;
width: 100%;
}
.input-group {
margin-top: 0.8rem;
}
.input-group small {
opacity: 0.4;
margin-left: 5px;
font-size: 10px;
}
.input-group.actions {
display: flex;
justify-content: space-between;
align-items: center;
}
.input-group.actions .button,
.input-group.actions button {
width: 48%;
margin: 0;
}
/* Main CSS */
#logo {
width: 40vh;
margin-left: -2vh;
}
#balance {
margin-top: -3rem;
color: white;
display: flex;
flex-wrap: wrap;
}
h2 {
font-weight: 400;
user-select: none;
padding-top: 10px;
padding-bottom: 6px;
}
h3 {
color: black;
}
.card {
display: flex;
flex-direction: column;
width: 100%;
background-color: white;
border-radius: 3px;
margin-right: 0;
padding: 5px 10px;
margin-bottom: 1.5rem;
box-shadow: 0px 1px 1px 0px rgba(59, 59, 59, 0.527);
}
.card h3 {
margin: 0;
margin-top: 5px;
font-size: 16px;
font-weight: 400;
user-select: none;
}
.card p {
margin-left: 1.5vw;
color: var(--darkblue);
margin-top: 0.5rem;
font-weight: 600;
font-size: 24px;
}
.card.total {
background: rgb(0, 190, 0);
margin-right: 0;
margin-left: 0;
}
.card.total p {
color: white;
}
.card.total h3 {
color: white;
}
.containerButtons {
display: flex;
justify-content: center;
}
.button {
text-decoration: none;
margin: 15px;
border: 1px solid;
padding: 1.5vh;
border-radius: 5px;
}
.button.save {
color: var(--green);
}
.button.withdraw {
color: red;
}
.button.ok {
color: white;
background-color: var(--green);
margin-left: 85%;
}
button {
width: 100%;
height: 50px;
background-color: var(--green);
color: white;
border: 0;
border-radius: 5px;
cursor: pointer;
font-weight: 400;
font-size: 16px;
}
button:hover {
box-shadow: 0px 0px 2px 1px green;
}
.button.cancel {
color: red;
height: 50px;
display: flex;
justify-content: center;
align-items: center;
font-weight: 400;
}
#data-table {
border-spacing: 0 0.5rem;
color: black;
}
#data-table th {
background: white;
color: #646464;
width: 50%;
font-weight: normal;
padding: 1rem 2rem;
user-select: none;
text-align: left;
}
#data-table tbody tr{
opacity: 0.7;
}
#data-table tbody tr:hover{
opacity: 1;
}
#data-table td {
background-color: white;
padding: 1rem 2rem;
}
td.price-transaction {
color: var(--darkblue);
}
td.withdraw {
color: red;
}
td.income {
color: green;
}
td.date {
color: var(--darkblue);
}
td.moneyatbank {
color: var(--darkblue);
}
/* Responsive */
#media screen and (min-width: 800px) {
#balance {
flex-wrap: nowrap;
}
.card {
margin-right: 2.5vh;
}
.card.total {
margin-left: 2.5vh;
}
}
#media screen and (max-width: 800px) {
#data-table {
display: block;
width: 100%;
border-spacing: 0 0.5rem;
color: black;
overflow: scroll;
}
}
<header>
<img src="assets/logo.svg" alt="Logo BiggyBank" id="logo">
</header>
<main class="container">
<section id="balance">
<h2 class="sr-only">Balanço</h2>
<div class="card">
<h3>Meta</h3>
<p>R$ 2000,00</p>
</div>
<div class="card total">
<h3>Total</h3>
<p id="totalCurrency"></p>
</div>
</section>
<section id="transaction">
<h2 class="sr-only">Transações</h2>
<div class="containerButtons">
+ Guardar
- Retirar
</div>
<table id="data-table">
<thead>
<tr>
<th>Tipo</th>
<th>Valor</th>
<th>Data</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</section>
</main>
<footer>
<img src="assets/darkmode.svg" alt="Icone DarkMode">
<img src="assets/lightmode.svg" alt="Icone DarkMode">
</footer>
<div class="modal1-overlay">
<div class="modal1">
<div id="form">
<h2>Guardar Dinheiro</h2>
<form action="" onsubmit="Form.submit(event)" id="form1">
<div class="input-group">
<label class="sr-only" for="amount">Valor à ser guardado</label>
<input id="amount" name="amount" type="number" step="0.01" placeholder="Valor à ser guardado" />
<small class="helpText">Use a vírgula (,) para casas decimais</small>
</div>
<div class="input-group">
<label class="sr-only" for="date">Valor à ser guardado</label>
<input id="date" name="date" type="date" />
</div>
<div class="input-group actions">
Cancelar
<button>Guardar</button>
</div>
</form>
</div>
</div>
</div>
<div class="modal2-overlay">
<div class="modal2">
<div id="form">
<h2>Retirar Dinheiro</h2>
<form action="" onsubmit="Form.submit(event)" id="form2">
<div class="input-group">
<label class="sr-only" for="amount2">Valor à ser guardado</label>
<input id="amount2" name="amount2" type="number" step="0.01" placeholder="Valor à ser guardado" />
<small class="helpText">Use a vírgula (,) para casas decimais</small>
</div>
<div class="input-group">
<label class="sr-only" for="date2">Valor à ser guardado</label>
<input id="date2" name="date2" type="date" />
</div>
<div class="input-group actions">
Cancelar
<button>Retirar</button>
</div>
</form>
</div>
</div>
</div>
<div class="modalError-overlay">
<div class="modalErrorContainer">
<h3 id="errorMessage"></h3>
OK
</div>
</div>

How to show 1 form at a time on a page using JavaScript

I'm creating lists which contain cards that are created by the user via forms.
The issue that I'm having here is that I want to show only 1 add-item-form form * on the page at a time (Not 1 form in each list but 1 form on the page overall). So, If a user creates multiple lists, then opens a form by clicking on the Add a card button, and then goes and click on another Add a card button from another list on the page, the first form should disappear, and a new form should appear in the list that it was clicked. Right now, multiple forms are being shown in different lists when I click the Add a card button, especially whenever I create multiple lists.
So basically, whenever Add a card is clicked, if a form is already open somewhere else, it will be closed and a new form will be opened within the list that I clicked the Add a card button.
I hope my explanation is useful. A sample of the code is shown below.
Here's a link to the code on [Codepen][https://codepen.io/Joanc/pen/MZjJvy]1.
Your help will be appreciated.
ATTENTION: I only want to change the cards form with class add-item-form not the list form with id add-list-form. The (grey) lists are fine, my only issue is with the cards.
// *************** ADD LISTS ***************
// add new list submit eventlistener
document.getElementById("add-list-form").addEventListener("submit", addList);
function addList(e) {
e.preventDefault();
const input = document.getElementById("list-name");
const name = input.value;
input.value = '';
if ('' == name) {
return;
}
const list = document.createElement('div');
list.setAttribute('class', 'list');
list.innerHTML =
`<div class="list-container">
<div class="list-heading" >
<h3 contenteditable="true">` + name + `</h3>
<div class= "ellipsis">…</div>
</div>
<div>
<div class="link-wrapper">
<a href="#" id="show-card-form" onclick="hideSHowForm('add-item-form', 'show-card-form');">
<span class="placeholder"><i class="fas fa-plus"></i> Add a card</span>
<span class="placeholder"><i class="fas fa-plus"></i> Add another card</span>
</a>
</div>
<form class="add-item-form">
<textarea placeholder="Enter a title for this card..."></textarea>
<div>
<input type="submit" value="Add Card">
<input type="button" value="X" onclick="hideSHowForm('add-item-form', 'show-card-form');">
<div class= "ellipsis">…</div>
</div>
</form>
</div>
</div>`;
document.getElementById("list-wrapper").appendChild(list);
}
// add new item submit eventlistener
document.addEventListener('submit', function(e) {
if (e.target.matches('.add-item-form')) {
e.preventDefault();
const textarea = e.target.getElementsByTagName('textarea')[0];
const text = textarea.value;
textarea.value = '';
if ('' == text) {
return;
}
//create card
const cardItem = document.createElement('p');
const card = document.createElement('div');
card.setAttribute('class', 'card');
//create pen icon
const pen = document.createElement('a');
pen.innerHTML = '<i class="fas fa-pen"></i>';
cardItem.innerHTML = text;
card.appendChild(cardItem)
card.appendChild(pen);
e.target.parentElement.prepend(card);
}
});
let spans = document.getElementsByClassName("placeholder");
//toggle between 'add a list' and 'add another list' links
window.onload = function(){
spans[1].style.display='none';
document.forms[0].style.display='none';
};
let clicked = 0;
//toggle between links and 'add-list-form'
function toggleDiv(formId, linkId){
clicked++;
if(document.getElementById( formId ).style.display == 'block'){
document.getElementById( formId ).style.display = 'none';
document.getElementById( linkId ).style.display = 'block';
}else{
document.getElementById( linkId ).style.display = 'none';
document.getElementById( formId ).style.display = 'block'
}if(clicked > 0) {
spans[0].style.display='none';
spans[1].style.display='block';
}
}
//toggle between links and 'add-list-form'
function hideSHowForm(form, link){
// var getForm = document.getElementsByClassName("listContainer");
for (var i=0;i<document.getElementsByClassName(form).length;i++){
// getForm[i].style.display = 'block';
if(document.getElementsByClassName(form )[i].style.display == 'block'){
document.getElementsByClassName(form)[i].style.display = 'none';
document.getElementById(link).style.display = 'block';
}else{
document.getElementById(link).style.display = 'none';
document.getElementsByClassName(form)[i].style.display = 'block'
}if(clicked > 0) {
spans[0].style.display='none';
spans[1].style.display='block';
}
}
}
// function showTitleAndCardSection(){
// var showCardSection = document.getElementsByClassName("listContainer");
// for (var i=0;i<showCardSection.length;i+=1){
// showCardSection [i].style.display = 'block';
// }
//}
/*************** ADD LISTS ***************/
.work-board {
background-color: transparent;
border-radius: 5px;
display: flex;
flex-direction: row;
}
#list-wrapper {
margin: 8px 5px 10px 0px;
padding: 2px;
border-radius: 4px;
background: transparent;
border: none;
display: flex;
flex-direction: row;
}
.list {
background: transparent;
}
.list-container {
padding: 4px 8px;
border-radius: 4px;
width: 256px;
background-color: rgb(226,228,230);
border: none;
margin: 2px 5px;
}
.list-heading {
display: flex;
flex-direction: row;
padding-bottom: 3px;
margin-bottom: 5px;
}
.list .list-heading h3 {
margin: 2px 3px 0px 0px;
width: 82%;
border-radius: 4px;
outline:none;
font-size: 14px;
font-weight: 600;
padding: 5px;
}
.list .list-heading h3:focus{
border: solid 2px rgb(91,164,207);
background-color: rgb(255, 255, 255);
}
.ellipsis {
/* display: inline-block; */
width: 30px;
text-align: center;
border-radius: 4px;
margin: 0px 1px 0px 0px;
padding: 0px;
float: right;
}
.ellipsis:hover {
background-color: rgba(131, 140, 145, 0.2)
}
form.add-item-form .ellipsis{
margin-top: 5px;
padding-bottom: 5px;
}
a {
text-decoration: none;
color: rgb(131, 140, 145);
font-size: 19px;
vertical-align:middle;
/* line-height:3px; */
text-align:center;
}
form#add-list-form {
margin-top: 12px;
width: 270px;
}
.form-inner-container {
background-color: rgb(226,228,230);
padding: 5px 5px 0px 5px;
border-radius: 4px;
}
input[type=text] {
height: 32px;
display: block;
border-radius: 4px;
border: solid 1px rgb(91,164,207);
width: 247px;
font-size: 14px;
outline: none;
box-shadow: 0 0 0 1px rgb(91,164,207);
word-wrap: break-word;
overflow: hidden;
color: rgb(131, 140, 145);
padding-left: 10px;
}
input[type=submit] {
outline: none;
font-size: 14px;
font-weight: 700;
color: rgb(255, 255, 255);
padding: 8px 13px;
background-color: rgb(90, 172, 68);
box-shadow: 0 1px 0 0 rgb(63, 111, 33);
border: none;
border-radius: 4px;
margin: 10px 0;
}
input[type=submit]:hover {
background-color: rgb(71, 138, 53);
}
input[type=button]{
margin-right: -5px;
border: none;
background-color: transparent;
font-size: 18px;
font-weight: 500;
color: rgb(131, 140, 145);
}
input[type=button]:hover{
color: rgb(103,109,112);
}
form.add-item-form {
margin-top: 20px;
}
form.add-item-form textarea {
outline: none;
width: 92%;
height: 50px;
max-height: 120px;
padding: 10px;
font-size: 14px;
box-shadow: 0px 1px 0px 0 rgba(1, 1, 1, 0.2);
border: none;
border-radius: 3px;
display: block;
word-wrap: break-word;
resize: none;
margin-top: -5px;
}
.card {
width: 92%;
box-shadow: 0px 1px 0px 0 rgba(1, 1, 1, 0.2);
border: none;
border-radius: 3px;
background-color: rgb(255, 255, 255);
min-height: 18px;
word-wrap: break-word;
padding: 0px 10px;
margin-top: 9px;
display: flex;
flex-direction: row;
position: relative;
}
.card:hover {
background-color: rgba(248,249,249,0.7);
}
.card p{
position: relative;
padding: 0px;
margin: 6px 0;
font-size: 14px;
z-index: 1;
}
.card a{
position: absolute;
margin-left: 220px;
z-index: 2;
}
.fa-pen {
font-size: 10px;
margin: 0;
padding: 7px;
border-radius: 4px;
}
.fa-pen:hover {
background-color: rgb(226,228,230);
}
#add-list-form, .add-item-form {
display: none;
}
.link-wrapper {
display: inline-block;
margin-top: 20px;
}
a#show-list-form {
text-decoration: none;
color: rgb(255, 255, 255);
background-color: rgba(1, 1, 1, 0.3);
padding: 10px 15px 10px 20px;
width: 242px;
text-align: left;
border-radius: 4px;
font-size: 14px;
height: 17px;
}
a#show-list-form:hover {
background-color: rgba(1, 1, 1, 0.4);
}
a#show-list-form span:first-child {
padding-right: 172px;
}
a#show-list-form span:nth-child(2), a#show-card-form span:nth-child(2){
display: none; /* hides the 'Add another link' when window loads */
}
<div class="board-wrapper">
<div id="workBoard" class="work-board">
<div id="list-wrapper"></div>
<div class="link-wrapper">
<a href="#" id="show-list-form" onclick="toggleDiv('add-list-form', 'show-list-form');">
<span class="placeholder"><i class="fas fa-plus"></i> Add a list</span>
<span class="placeholder"><i class="fas fa-plus"></i> Add another list</span>
</a>
</div>
<form id="add-list-form">
<div class="form-inner-container">
<input type="text" id="list-name" placeholder="Enter list title..." autocomplete="off">
<input type="submit" value="Add List">
<!-- <input type="button" onclick="toggleDiv('add-list-form', 'show-list-form');"><i class="fas fa-times"></i></input> -->
<input type="button" onclick="toggleDiv('add-list-form', 'show-list-form')" value="X">
</div>
</form>
</div>
</div><!-- end of board-wrapper -->
It happens because you iterate with for loop over all add-item-form elements and add those styles. You add inline events listeners in addList() and you are not able to specify which of those elements were actually clicked, since you can't catch an event. I know how frustrating it may sound to you but I would recommend trying to write it all over again but keeping good practices. I advise you to use innerHTML as little you can, don't add inline styles to HTML in JS. Rather create classes that match your expectations like shown, hidden, style them and add them to events. Also use addEventListener instead of adding onclick() in HTML. You are really close to getting what you want, but its pretty messed up in this form.
Edit: The simplest workaround I can give you is this, but there is still much work to be done there:
// *************** ADD LISTS ***************
// add new list submit eventlistener
document.getElementById("add-list-form").addEventListener("submit", addList);
//Declaring index
var listIndex = 0
function addList(e) {
e.preventDefault();
const input = document.getElementById("list-name");
const name = input.value;
input.value = '';
if ('' == name) {
return;
}
const list = document.createElement('div');
list.setAttribute('class', 'list');
list.innerHTML =
`<div class="list-container">
<div class="list-heading" >
<h3 contenteditable="true">` + name + `</h3>
<div class= "ellipsis">…</div>
</div>
<div>
<div class="link-wrapper">
<a href="#" id="show-card-form" onclick="hideSHowForm('add-item-form', 'show-card-form', ` + listIndex + `);">
<span class="placeholder"><i class="fas fa-plus"></i> Add a card</span>
<span class="placeholder"><i class="fas fa-plus"></i> Add another card</span>
</a>
</div>
<form class="add-item-form">
<textarea placeholder="Enter a title for this card..."></textarea>
<div>
<input type="submit" value="Add Card">
<input type="button" value="X" onclick="hideSHowForm('add-item-form', 'show-card-form');">
<div class= "ellipsis">…</div>
</div>
</form>
</div>
</div>`;
//Increasing index
listIndex++
document.getElementById("list-wrapper").appendChild(list);
}
// add new item submit eventlistener
document.addEventListener('submit', function(e) {
if (e.target.matches('.add-item-form')) {
e.preventDefault();
const textarea = e.target.getElementsByTagName('textarea')[0];
const text = textarea.value;
textarea.value = '';
if ('' == text) {
return;
}
//create card
const cardItem = document.createElement('p');
const card = document.createElement('div');
card.setAttribute('class', 'card');
//create pen icon
const pen = document.createElement('a');
pen.innerHTML = '<i class="fas fa-pen"></i>';
cardItem.innerHTML = text;
card.appendChild(cardItem)
card.appendChild(pen);
e.target.parentElement.prepend(card);
}
});
let spans = document.getElementsByClassName("placeholder");
//toggle between 'add a list' and 'add another list' links
window.onload = function(){
spans[1].style.display='none';
document.forms[0].style.display='none';
};
let clicked = 0;
//toggle between links and 'add-list-form'
function toggleDiv(formId, linkId){
clicked++;
if(document.getElementById( formId ).style.display == 'block'){
document.getElementById( formId ).style.display = 'none';
document.getElementById( linkId ).style.display = 'block';
}else{
document.getElementById( linkId ).style.display = 'none';
document.getElementById( formId ).style.display = 'block'
}if(clicked > 0) {
spans[0].style.display='none';
spans[1].style.display='block';
}
}
document.getElementsByClassName('')
//toggle between links and 'add-list-form'
function hideSHowForm(form, link, id){
// var getForm = document.getElementsByClassName("listContainer");
// getForm[i].style.display = 'block';
if(document.getElementsByClassName(form)[id].style.display == 'block'){
document.getElementsByClassName(form)[id].style.display = 'none';
document.getElementById(link).style.display = 'block';
}else{
document.getElementById(link).style.display = 'none';
document.getElementsByClassName(form)[id].style.display = 'block'
}if(clicked > 0) {
spans[0].style.display='none';
spans[1].style.display='block';
}
}
// function showTitleAndCardSection(){
// var showCardSection = document.getElementsByClassName("listContainer");
// for (var i=0;i<showCardSection.length;i+=1){
// showCardSection [i].style.display = 'block';
// }
/*************** ADD LISTS ***************/
.work-board {
background-color: transparent;
border-radius: 5px;
display: flex;
flex-direction: row;
}
#list-wrapper {
margin: 8px 5px 10px 0px;
padding: 2px;
border-radius: 4px;
background: transparent;
border: none;
display: flex;
flex-direction: row;
}
.list {
background: transparent;
}
.list-container {
padding: 4px 8px;
border-radius: 4px;
width: 256px;
background-color: rgb(226,228,230);
border: none;
margin: 2px 5px;
}
.list-heading {
display: flex;
flex-direction: row;
padding-bottom: 3px;
margin-bottom: 5px;
}
.list .list-heading h3 {
margin: 2px 3px 0px 0px;
width: 82%;
border-radius: 4px;
outline:none;
font-size: 14px;
font-weight: 600;
padding: 5px;
}
.list .list-heading h3:focus{
border: solid 2px rgb(91,164,207);
background-color: rgb(255, 255, 255);
}
.ellipsis {
/* display: inline-block; */
width: 30px;
text-align: center;
border-radius: 4px;
margin: 0px 1px 0px 0px;
padding: 0px;
float: right;
}
.ellipsis:hover {
background-color: rgba(131, 140, 145, 0.2)
}
form.add-item-form .ellipsis{
margin-top: 5px;
padding-bottom: 5px;
}
a {
text-decoration: none;
color: rgb(131, 140, 145);
font-size: 19px;
vertical-align:middle;
/* line-height:3px; */
text-align:center;
}
form#add-list-form {
margin-top: 12px;
width: 270px;
}
.form-inner-container {
background-color: rgb(226,228,230);
padding: 5px 5px 0px 5px;
border-radius: 4px;
}
input[type=text] {
height: 32px;
display: block;
border-radius: 4px;
border: solid 1px rgb(91,164,207);
width: 247px;
font-size: 14px;
outline: none;
box-shadow: 0 0 0 1px rgb(91,164,207);
word-wrap: break-word;
overflow: hidden;
color: rgb(131, 140, 145);
padding-left: 10px;
}
input[type=submit] {
outline: none;
font-size: 14px;
font-weight: 700;
color: rgb(255, 255, 255);
padding: 8px 13px;
background-color: rgb(90, 172, 68);
box-shadow: 0 1px 0 0 rgb(63, 111, 33);
border: none;
border-radius: 4px;
margin: 10px 0;
}
input[type=submit]:hover {
background-color: rgb(71, 138, 53);
}
input[type=button]{
margin-right: -5px;
border: none;
background-color: transparent;
font-size: 18px;
font-weight: 500;
color: rgb(131, 140, 145);
}
input[type=button]:hover{
color: rgb(103,109,112);
}
form.add-item-form {
margin-top: 20px;
}
form.add-item-form textarea {
outline: none;
width: 92%;
height: 50px;
max-height: 120px;
padding: 10px;
font-size: 14px;
box-shadow: 0px 1px 0px 0 rgba(1, 1, 1, 0.2);
border: none;
border-radius: 3px;
display: block;
word-wrap: break-word;
resize: none;
margin-top: -5px;
}
.card {
width: 92%;
box-shadow: 0px 1px 0px 0 rgba(1, 1, 1, 0.2);
border: none;
border-radius: 3px;
background-color: rgb(255, 255, 255);
min-height: 18px;
word-wrap: break-word;
padding: 0px 10px;
margin-top: 9px;
display: flex;
flex-direction: row;
position: relative;
}
.card:hover {
background-color: rgba(248,249,249,0.7);
}
.card p{
position: relative;
padding: 0px;
margin: 6px 0;
font-size: 14px;
z-index: 1;
}
.card a{
position: absolute;
margin-left: 220px;
z-index: 2;
}
.fa-pen {
font-size: 10px;
margin: 0;
padding: 7px;
border-radius: 4px;
}
.fa-pen:hover {
background-color: rgb(226,228,230);
}
#add-list-form, .add-item-form {
display: none;
}
.link-wrapper {
display: inline-block;
margin-top: 20px;
}
a#show-list-form {
text-decoration: none;
color: rgb(255, 255, 255);
background-color: rgba(1, 1, 1, 0.3);
padding: 10px 15px 10px 20px;
width: 242px;
text-align: left;
border-radius: 4px;
font-size: 14px;
height: 17px;
}
a#show-list-form:hover {
background-color: rgba(1, 1, 1, 0.4);
}
a#show-list-form span:first-child {
padding-right: 172px;
}
a#show-list-form span:nth-child(2), a#show-card-form span:nth-child(2){
display: none; /* hides the 'Add another link' when window loads */
}
<div class="board-wrapper">
<div id="workBoard" class="work-board">
<div id="list-wrapper"></div>
<div class="link-wrapper">
<a href="#" id="show-list-form" onclick="toggleDiv('add-list-form', 'show-list-form');">
<span class="placeholder"><i class="fas fa-plus"></i> Add a list</span>
<span class="placeholder"><i class="fas fa-plus"></i> Add another list</span>
</a>
</div>
<form id="add-list-form">
<div class="form-inner-container">
<input type="text" id="list-name" placeholder="Enter list title..." autocomplete="off">
<input type="submit" value="Add List">
<!-- <input type="button" onclick="toggleDiv('add-list-form', 'show-list-form');"><i class="fas fa-times"></i></input> -->
<input type="button" onclick="toggleDiv('add-list-form', 'show-list-form')" value="X">
</div>
</form>
</div>
</div><!-- end of board-wrapper -->
Just add these two lines above your const list = document.createElement('div'); line inside your addList() function like this:
var listWrap = document.getElementById("list-wrapper");
listWrap.innerHTML = "";
What the above does is assign the list-wrapper div to a variable called listWrap and then reset the list-wrapper div to an empty div whenever someone tries to submit a new form. After emptying the list-wrapper div, the function then proceeds to add the new "add-item-form form" submitted to the empty list-wrapper div.
Run the Code Snippet below to see how the above two lines work:
// *************** ADD LISTS ***************
// add new list submit eventlistener
document.getElementById("add-list-form").addEventListener("submit", addList);
function addList(e) {
e.preventDefault();
const input = document.getElementById("list-name");
const name = input.value;
input.value = '';
if ('' == name) {
return;
}
var listWrap = document.getElementById("list-wrapper");
listWrap.innerHTML = "";
const list = document.createElement('div');
list.setAttribute('class', 'list');
list.innerHTML =
`<div class="list-container">
<div class="list-heading" >
<h3 contenteditable="true">` + name + `</h3>
<div class= "ellipsis">…</div>
</div>
<div>
<div class="link-wrapper">
<a href="#" id="show-card-form" onclick="hideSHowForm('add-item-form', 'show-card-form');">
<span class="placeholder"><i class="fas fa-plus"></i> Add a card</span>
<span class="placeholder"><i class="fas fa-plus"></i> Add another card</span>
</a>
</div>
<form class="add-item-form">
<textarea placeholder="Enter a title for this card..."></textarea>
<div>
<input type="submit" value="Add Card">
<input type="button" value="X" onclick="hideSHowForm('add-item-form', 'show-card-form');">
<div class= "ellipsis">…</div>
</div>
</form>
</div>
</div>`;
document.getElementById("list-wrapper").appendChild(list);
}
// add new item submit eventlistener
document.addEventListener('submit', function(e) {
if (e.target.matches('.add-item-form')) {
e.preventDefault();
const textarea = e.target.getElementsByTagName('textarea')[0];
const text = textarea.value;
textarea.value = '';
if ('' == text) {
return;
}
//create card
const cardItem = document.createElement('p');
const card = document.createElement('div');
card.setAttribute('class', 'card');
//create pen icon
const pen = document.createElement('a');
pen.innerHTML = '<i class="fas fa-pen"></i>';
cardItem.innerHTML = text;
card.appendChild(cardItem)
card.appendChild(pen);
e.target.parentElement.prepend(card);
}
});
let spans = document.getElementsByClassName("placeholder");
//toggle between 'add a list' and 'add another list' links
window.onload = function(){
spans[1].style.display='none';
document.forms[0].style.display='none';
};
let clicked = 0;
//toggle between links and 'add-list-form'
function toggleDiv(formId, linkId){
clicked++;
if(document.getElementById( formId ).style.display == 'block'){
document.getElementById( formId ).style.display = 'none';
document.getElementById( linkId ).style.display = 'block';
}else{
document.getElementById( linkId ).style.display = 'none';
document.getElementById( formId ).style.display = 'block'
}if(clicked > 0) {
spans[0].style.display='none';
spans[1].style.display='block';
}
}
//toggle between links and 'add-list-form'
function hideSHowForm(form, link){
// var getForm = document.getElementsByClassName("listContainer");
for (var i=0;i<document.getElementsByClassName(form).length;i++){
// getForm[i].style.display = 'block';
if(document.getElementsByClassName(form )[i].style.display == 'block'){
document.getElementsByClassName(form)[i].style.display = 'none';
document.getElementById(link).style.display = 'block';
}else{
document.getElementById(link).style.display = 'none';
document.getElementsByClassName(form)[i].style.display = 'block'
}if(clicked > 0) {
spans[0].style.display='none';
spans[1].style.display='block';
}
}
}
// function showTitleAndCardSection(){
// var showCardSection = document.getElementsByClassName("listContainer");
// for (var i=0;i<showCardSection.length;i+=1){
// showCardSection [i].style.display = 'block';
// }
//}
/*************** ADD LISTS ***************/
.work-board {
background-color: transparent;
border-radius: 5px;
display: flex;
flex-direction: row;
}
#list-wrapper {
margin: 8px 5px 10px 0px;
padding: 2px;
border-radius: 4px;
background: transparent;
border: none;
display: flex;
flex-direction: row;
}
.list {
background: transparent;
}
.list-container {
padding: 4px 8px;
border-radius: 4px;
width: 256px;
background-color: rgb(226,228,230);
border: none;
margin: 2px 5px;
}
.list-heading {
display: flex;
flex-direction: row;
padding-bottom: 3px;
margin-bottom: 5px;
}
.list .list-heading h3 {
margin: 2px 3px 0px 0px;
width: 82%;
border-radius: 4px;
outline:none;
font-size: 14px;
font-weight: 600;
padding: 5px;
}
.list .list-heading h3:focus{
border: solid 2px rgb(91,164,207);
background-color: rgb(255, 255, 255);
}
.ellipsis {
/* display: inline-block; */
width: 30px;
text-align: center;
border-radius: 4px;
margin: 0px 1px 0px 0px;
padding: 0px;
float: right;
}
.ellipsis:hover {
background-color: rgba(131, 140, 145, 0.2)
}
form.add-item-form .ellipsis{
margin-top: 5px;
padding-bottom: 5px;
}
a {
text-decoration: none;
color: rgb(131, 140, 145);
font-size: 19px;
vertical-align:middle;
/* line-height:3px; */
text-align:center;
}
form#add-list-form {
margin-top: 12px;
width: 270px;
}
.form-inner-container {
background-color: rgb(226,228,230);
padding: 5px 5px 0px 5px;
border-radius: 4px;
}
input[type=text] {
height: 32px;
display: block;
border-radius: 4px;
border: solid 1px rgb(91,164,207);
width: 247px;
font-size: 14px;
outline: none;
box-shadow: 0 0 0 1px rgb(91,164,207);
word-wrap: break-word;
overflow: hidden;
color: rgb(131, 140, 145);
padding-left: 10px;
}
input[type=submit] {
outline: none;
font-size: 14px;
font-weight: 700;
color: rgb(255, 255, 255);
padding: 8px 13px;
background-color: rgb(90, 172, 68);
box-shadow: 0 1px 0 0 rgb(63, 111, 33);
border: none;
border-radius: 4px;
margin: 10px 0;
}
input[type=submit]:hover {
background-color: rgb(71, 138, 53);
}
input[type=button]{
margin-right: -5px;
border: none;
background-color: transparent;
font-size: 18px;
font-weight: 500;
color: rgb(131, 140, 145);
}
input[type=button]:hover{
color: rgb(103,109,112);
}
form.add-item-form {
margin-top: 20px;
}
form.add-item-form textarea {
outline: none;
width: 92%;
height: 50px;
max-height: 120px;
padding: 10px;
font-size: 14px;
box-shadow: 0px 1px 0px 0 rgba(1, 1, 1, 0.2);
border: none;
border-radius: 3px;
display: block;
word-wrap: break-word;
resize: none;
margin-top: -5px;
}
.card {
width: 92%;
box-shadow: 0px 1px 0px 0 rgba(1, 1, 1, 0.2);
border: none;
border-radius: 3px;
background-color: rgb(255, 255, 255);
min-height: 18px;
word-wrap: break-word;
padding: 0px 10px;
margin-top: 9px;
display: flex;
flex-direction: row;
position: relative;
}
.card:hover {
background-color: rgba(248,249,249,0.7);
}
.card p{
position: relative;
padding: 0px;
margin: 6px 0;
font-size: 14px;
z-index: 1;
}
.card a{
position: absolute;
margin-left: 220px;
z-index: 2;
}
.fa-pen {
font-size: 10px;
margin: 0;
padding: 7px;
border-radius: 4px;
}
.fa-pen:hover {
background-color: rgb(226,228,230);
}
#add-list-form, .add-item-form {
display: none;
}
.link-wrapper {
display: inline-block;
margin-top: 20px;
}
a#show-list-form {
text-decoration: none;
color: rgb(255, 255, 255);
background-color: rgba(1, 1, 1, 0.3);
padding: 10px 15px 10px 20px;
width: 242px;
text-align: left;
border-radius: 4px;
font-size: 14px;
height: 17px;
}
a#show-list-form:hover {
background-color: rgba(1, 1, 1, 0.4);
}
a#show-list-form span:first-child {
padding-right: 172px;
}
a#show-list-form span:nth-child(2), a#show-card-form span:nth-child(2){
display: none; /* hides the 'Add another link' when window loads */
}
<div class="board-wrapper">
<div id="workBoard" class="work-board">
<div id="list-wrapper"></div>
<div class="link-wrapper">
<a href="#" id="show-list-form" onclick="toggleDiv('add-list-form', 'show-list-form');">
<span class="placeholder"><i class="fas fa-plus"></i> Add a list</span>
<span class="placeholder"><i class="fas fa-plus"></i> Add another list</span>
</a>
</div>
<form id="add-list-form">
<div class="form-inner-container">
<input type="text" id="list-name" placeholder="Enter list title..." autocomplete="off">
<input type="submit" value="Add List">
<!-- <input type="button" onclick="toggleDiv('add-list-form', 'show-list-form');"><i class="fas fa-times"></i></input> -->
<input type="button" onclick="toggleDiv('add-list-form', 'show-list-form')" value="X">
</div>
</form>
</div>
</div><!-- end of board-wrapper -->

Change CSS of nth class in Jquery or Javascript

I am trying to change the text color of the 5th infobox (class) in my code below. The text color changes but for all the infoboxes.
//INFOBOX5
var json_data = {"headers":["Platform","Value1","value1","valueP1","valueP2"],"rows":[["platform2","xxx",404.07000000000005,1634,6364],["platform5","xxx",404.07000000000005,1634,6364],["platform1","xxx",352.8,1634,6364],["platform3","xxx",352.8,1634,6364],
["platform3","xxx",352.8,1634,6364],["platform4","xxx",352.8,1634,6364]]};
var platform_data = json_data.rows;
var platform1_element = document.getElementById("platform1");
var platform5_element = document.getElementById("platform5");
var platform6_element = document.getElementById("platform6");
var platform2_element = document.getElementById("platform2");
var platform3_element = document.getElementById("platform3");
var platform4_element = document.getElementById("platform4");
function onlyUnique(value, index, self) {
return self.indexOf(value) === index;
}
function formatNumber (num) {
return num.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,")
}
var platforms = [];
for (var i in platform_data) {
if (platform_data[i][0] != null){
platforms[i] = platform_data[i][0].toLowerCase();
}
}
var unique_platforms = platforms.filter( onlyUnique );
var target_width = 100/(unique_platforms.length-2);
var width_str=target_width+"%";
platform1_element.classList.add("hidden");
platform5_element.classList.add("hidden");
platform6_element.classList.add("hidden");
platform3_element.classList.add("hidden");
platform2_element.classList.add("hidden");
platform4_element.classList.add("hidden");
var total_value1 = 0;
var total_value2 = 0;
var total_display_value1 = 0;
var total_video_value1 = 0;
var total_mixed_value1 = 0;
var total_other_value1 = 0;
var total_display_value2 = 0;
var total_video_value2 = 0;
var total_mixed_value2 = 0;
var value2_numbers = [];
for (var i in unique_platforms) {
var platform_name = unique_platforms[i].toLowerCase();
var display_value1_total = 0;
var display_value2_total = 0;
var video_value1_total = 0;
var video_value2_total = 0;
var mixed_value1_total = 0;
var mixed_value2_total = 0;
var other_value1_total = 0;
for (var x in platform_data){
if (platform_data[x][0] != null){
if(platform_data[x][0].toLowerCase() == platform_name){
switch(platform_data[x][1]) {
case "display":
// Red Dot
display_value1_total = display_value1_total + platform_data[x][2];
total_value1 = total_value1 + display_value1_total;
break;
case "video":
video_value1_total = video_value1_total + platform_data[x][2];
total_value1 = total_value1 + video_value1_total;
break;
case "mixed":
mixed_value1_total = mixed_value1_total + platform_data[x][2];
total_value1 = total_value1 + mixed_value1_total;
break;
case "Other":
other_value1_total = other_value1_total + platform_data[x][2];
total_value1 = total_value1 + other_value1_total;
break;
default:
doNothing = "";
}
}
}else {
value2_numbers = platform_data[x];
}
}
var platform_value1 = display_value1_total + video_value1_total + mixed_value1_total + other_value1_total;
var generic_element = document.getElementById(platform_name);
var element_value1_name = platform_name+"_value1";
var fl_value1 = parseFloat(platform_value1).toFixed(0);
var curr_flag = "€"+formatNumber(fl_value1);
document.getElementById(element_value1_name).innerHTML = curr_flag;
total_display_value1 = total_display_value1 + display_value1_total;
total_video_value1 = total_video_value1 + video_value1_total;
total_mixed_value1 = total_mixed_value1 + mixed_value1_total;
}
var total_value1_string = "<h1>€" + formatNumber(Number(total_value1).toFixed(0)) + "</h1>";
//document.getElementById("total_value1").innerHTML = total_value1_string;
if (value2_numbers.length == 0){
value2_numbers = platform_data[0];
}
var fl_value2 = 0;
var curr_flag_bud = '';
var element_value2_name = '';
for (var i in json_data.headers){
switch(json_data.headers[i]) {
case "valueP1":
element_value2_name = "platform1_value2";
fl_value2 = parseFloat(value2_numbers[i]).toFixed(0);
curr_flag_bud = "€"+formatNumber(fl_value2);
document.getElementById(element_value2_name).innerHTML = curr_flag_bud;
break;
case "valueP2":
element_value2_name = "platform2_value2";
fl_value2 = parseFloat(value2_numbers[i]).toFixed(0);
curr_flag_bud = "€" +formatNumber(fl_value2);
document.getElementById(element_value2_name).innerHTML = curr_flag_bud;
break;
case "valueP1":
element_value2_name = "platform1_value2";
fl_value2 = parseFloat(value2_numbers[i]).toFixed(0);
curr_flag_bud = "€" +formatNumber(fl_value2);
document.getElementById(element_value2_name).innerHTML = curr_flag_bud;
break;
default:
}
}
var statBox = Array.from(document.querySelectorAll('.infobox'));
var element_id;
var parentBoxlist = Array.from(document.querySelectorAll('.parentbox'));
var channel_value1_check = 0;
var value1_channels = [];
// if (total_mixed_value1 > 0.0) {channel_value1_check = channel_value1_check + 1;value1_channels[0] = 'mixed';};
// if (total_video_value1 > 0.0) {channel_value1_check = channel_value1_check + 1;value1_channels[1] = 'video';};
// if (total_display_value1 > 0.0) {channel_value1_check = channel_value1_check + 1;value1_channels[2] = 'display';};
statBox.forEach(function(box) {
switch(unique_platforms.length) {
case 1:
// 1 box
element_id = box.getAttribute('id');
if (unique_platforms.includes(element_id)){
box.classList.add('infobox1');
box.classList.remove('hidden');
}
break;
case 2:
// 2 box's
element_id = box.getAttribute('id');
if (unique_platforms.includes(element_id)){
box.classList.add('infobox2');
box.classList.remove('hidden');
}
break;
case 3:
// 3 box's
element_id = box.getAttribute('id');
if (unique_platforms.includes(element_id)){
box.classList.add('infobox3');
box.classList.remove('hidden');
}
break;
case 4:
// 4 box's
element_id = box.getAttribute('id');
if (unique_platforms.includes(element_id)){
box.classList.add('infobox4');
box.classList.remove('hidden');
}
break;
case 5:
// 5 box's
element_id = box.getAttribute('id');
if (unique_platforms.includes(element_id)){
box.classList.add('infobox5');
box.classList.remove('hidden');
}
break;
default:
}
});
$(".boxbox:nth-of-type(1)").css("color", "#fff");
#import url('https://fonts.googleapis.com/css?family=Roboto');
body{
color: #fff;
font-family: Roboto;
margin:0;
overflow:hidden;
}
h1{
font-size: 1.2vw;
}
h3{
font-size: 1.1vw!important;
font-weight: 100;
margin: 0;
padding: 5px;
}
.redSq{
background-color: #ff000a;
width: 117px;
height: 241px;
float:left;
}
.row {
display: table;
width: 99.8%;
height: 180px;
color: #454545;
background-color:#dee9f3;
//border: solid 1px #454545;
box-shadow: 1px 2px 4px rgba(0, 0, 0, .5);
margin-bottom: 10px;
}
.row > .col-lg-6 {
display: table-cell;
vertical-align: middle;
}
.container {
display: flex;
flex-wrap: wrap;
}
.container > div {
padding: 15px;
margin: 5px;
flex: 0 0 calc(100% - 20px);
text-align: left;
}
td{
padding: 2px 2px;
text-align: center;
margin: 6px 0;
border: none;
}
table{
width: 100%;
background-color:#454545;
font-weight:500;
border-collapse: separate;
border-spacing:0.3em 1.1em;
color: #fff;
border: 0;
}
p{
font-size: 1.2vw;
}
.boxes{
padding-top: 40px;
padding-left: 30px;
padding-right: 5%;
min-width: 200px;
float:left;
display: inline-block;
}
#line{
border-bottom: solid 1px #CCC;
margin-top: 0px;
padding-top: 15px;
}
.infobox {
float:left;
margin: 0;
box-shadow: 1px 2px 4px rgba(0, 0, 0, .5);
color: #454545;
}
.infobox1 {
float:left;
min-height:150px;
min-width: 100%;
margin: 0;
}
.infobox2 {
float:left;
min-height:150px;
min-width: 49%;
margin: 0 0.5%;
//padding: 18px 0;
}
.infobox3 {
float:left;
min-height:150px;
min-width: 32.33%;
margin: 0 0.5%;
//padding: 18px 0;
}
.infobox4 {
float:left;
//min-height:150px;
min-width: 23.9%;
margin: 0 0.5%;
//padding: 18px 0;
}
.infobox5 {
float:left;
min-height:150px;
min-width: 32.33%;
margin: 0 0.5% 0.7%;
//padding: 18px 0;
}
div.leftBox{
float:left;
width:60%;
margin: 15px 0 0 25px;
font-size: 1.1vw;
}
div.rightBox{
float:left;
width: 60%;
margin: 15px 0 0 25px;
font-size: 1.1vw;
}
.infocontentheader {
//text-align: center;
line-height: 2.8;
//color: #fff;
vertical-align: middle;
height: 100%;
float:left;
width:25%;
}
.infocontent{
text-align: center;
color: #fff;
width: 50%;
float: left;
}
div#platform1.infocontentheader{
background-color: #3c5999;
}
div#platform1.infobox img{
display: block;
margin: 0 auto 0 auto;
}
p#sTitle {
font-weight: 900;
font-size: 1.5vw;
}
p#bTitle {
//font-weight: 900;
font-size: 1.2vw;
}
p#platform1_value1, p#platform5_value1, p#platform4_value1 ,p#platform3_value1,
p#platform2_value1, p#twitter_value1 {
font-weight: 900;
font-size: 1.3em;
margin: 10px 0 0 20px;
}
p#platform1_budget, p#platform5_budget, p#platform4_budget, p#platform3_budget,
p#platform2_budget, p#twitter_budget{
font-size: 1.2em;
margin: 10px 0 0 20px;
}
div#twitter.infocontentheader{
background-color: #1da1f2;
}
div#twitter.infobox img{
display: block;
margin: 0 auto 0 auto;
}
div#platform3.infocontentheader{
background-color: #a15aa0;
}
div#display.parentbox{
background-color: #b3b3b3;
color: #fff;
}
div#video.parentbox{
background-color: #999999;
color: #fff;
}
div#mixed.parentbox{
background-color: #c1c1c1;
color: #fff;
}
#platform3 div.infocontentheader{
color: #fff;
}
div#platform3.infobox img{
display: block;
margin: 0 auto 0 auto;
}
div#platform3_value.infocontent{
color: #000;
}
div#platform5.infocontentheader{
background-color: #ff0102;
}
div#platform5.infobox img{
display: block;
margin: 0 auto 0 auto;
}
div#platform4.infocontentheader{
background-color: #cac9c2;
}
div#platform4.infobox img{
display: block;
margin: 10% auto 0 auto;
}
div#platform2.infobox{
background-color: #fff;
}
div#platform2.infobox img{
display: block;
margin: 10% auto 0 auto;
}
.hidden{
display:none;
}
#parent_div_1{
width:50%;
min-height: 150px;
background-color: #757476;
margin-right:0px;
float:left;
}
#parent_div_2{
width:50%;
min-height: 150px;
background-color: #8D8D8D;
margin-right:0px;
float:left;
}
.parentbox{
width:33.33%;
min-height: 150px;
/*background-color: #8D8D8D;*/
margin-right:0px;
float:left;
}
.parentbox1{
width:100%;
min-height: 150px;
margin-right:0px;
float:left;
}
.parentbox2{
width:50%;
min-height: 150px;
margin-right:0px;
float:left;
}
.parentbox3{
width:33.33%;
min-height: 150px;
margin-right:0px;
float:left;
}
.child_div_1{
margin-top: 50px;
margin-left: 15%;
margin-bottom: 0px;
text-align: left;
}
.child_div_2{
margin-left: 15%;
margin-top: 10px;
margin-bottom: 40px;
text-align: left;
}
.child_budget{
margin-top: 10px;
margin-bottom: 40px;
padding-left:15%;
text-align: left;
float: left;
}
.child_value1{
margin-top: 10px;
margin-bottom: 40px;
padding-right: 15%;
text-align: left;
float:right;
}
.child_title{
margin-top: 50px;
margin-bottom: 0px;
text-align: center;
}
.child_budget_number{
padding-right: 20%;
}
.child_value1_number{
padding-left: 20%;
}
.boxbox {
display: table;
width: 99.8%;
height: 160px;
color: #454545;
font-size:1.1vw;
}
.boxbox {
float:left;
display: table;
width: 99.8%;
height: 180px;
color: #454545;
}
.boxbox > .col-lg-6 {
display: table-cell;
vertical-align: middle;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div id="wrapper2" style="height:160px;">
<div class="infobox" id="platform1">
<div class="boxbox">
<div class="col-lg-6" style="background-color: #3c5999; min-width: 50px;">
<img src="">
</div>
<div class="col-lg-6" style="float: left;">
<div class="container">
<div id="sTitle">value1<br>
<div id="platform1_value1"></div>
</div>
<div id="bTitle">value2<br>
<div id="platform1_value2"></div>
</div>
</div>
</div>
</div>
</div>
<div class="infobox" id="platform6">
<div class="boxbox">
<div class="col-lg-6" style="background-color: #3c5999; min-width: 50px;">
<img src="">
</div>
<div class="col-lg-6" style="float: left;">
<div class="container">
<div id="sTitle">value1<br>
<div id="platform6_value1"></div>
</div>
<div id="bTitle">value2<br>
<div id="platform6_value2"></div>
</div>
</div>
</div>
</div>
</div>
<div class="infobox" id="platform3">
<div class="boxbox">
<div class="col-lg-6" style="background-color: #a15aa0; min-width: 50px;">
<img src="">
</div>
<div class="col-lg-6" style="float: left;">
<div class="container">
<div id="sTitle">value1<br>
<div id="platform3_value1"></div>
</div>
<div id="bTitle">value2<br>
<div id="platform3_value2"></div>
</div>
</div>
</div>
</div>
</div>
<div class="infobox" id="platform5">
<div class="boxbox" id="platform5">
<div class="col-lg-6" style="background-color: #ff0102; min-width: 50px;">
<img src="">
</div>
<div class="col-lg-6" style="float: left;">
<div class="container">
<div id="sTitle">value1<br>
<div id="platform5_value1"></div>
</div>
<div id="bTitle">value2<br>
<div id="platform5_value2"></div>
</div>
</div>
</div>
</div>
</div>
<div class="infobox" id="platform4">
<div class="boxbox">
<div class="col-lg-6" style="background-color: #cac9c2; min-width: 50px;">
<img src="">
</div>
<div class="col-lg-6" style="float: left;">
<div class="container">
<div id="sTitle">value1<br>
<div id="platform4_value1"></div>
</div>
<div id="bTitle">value2<br>
<div id="platform4_value2"></div>
</div>
</div>
</div>
</div>
</div>
<div class="infobox" id="platform2">
<div class="boxbox" id="platform2">
<div class="col-lg-6" style="background-color: #8a3ab9; min-width: 50px;">
<img src="">
</div>
<div class="col-lg-6" style="float: left;">
<div class="container">
<div id="sTitle">value1<br>
<div id="platform2_value1"></div>
</div>
<div id="bTitle">value2<br>
<div id="platform2_value2"></div>
</div>
</div>
</div>
</div>
</div>
</div>
Your direct child of class container infobox5 is overwriting the CSS color for your Jquery method. You have to remove it first and then use it as demonstrated below:
Note- .eq(index) is better suited for your query in contrast to :nth-of-type(index). You can try them both and see it for yourself.
Pointer:
Clean up your CSS, a lot of unecessary styles have been implemented but for this query, as mentioned by the other answer as well .boxbox class is implementing its own color style and as mentioned the child of div with class infobox5 is also implementing its own color style which overrides the JQuery css being implemented on the parent container.
$(".infobox5").eq(4).css("color", "green"); //Index starts from 0 for 1st element, 1 for 2nd and so on 4 for 5th element of type .infobox5
#import url('https://fonts.googleapis.com/css?family=Roboto');
body {
color: #fff;
font-family: Roboto;
margin: 0;
overflow: hidden;
}
h1 {
font-size: 1.2vw;
}
h3 {
font-size: 1.1vw!important;
font-weight: 100;
margin: 0;
padding: 5px;
}
.redSq {
background-color: #ff000a;
width: 117px;
height: 241px;
float: left;
}
.row {
display: table;
width: 99.8%;
height: 180px;
color: #454545;
background-color: #dee9f3;
//border: solid 1px #454545;
box-shadow: 1px 2px 4px rgba(0, 0, 0, .5);
margin-bottom: 10px;
}
.row>.col-lg-6 {
display: table-cell;
vertical-align: middle;
}
.container {
display: flex;
flex-wrap: wrap;
}
.container>div {
padding: 15px;
margin: 5px;
flex: 0 0 calc(100% - 20px);
text-align: left;
}
td {
padding: 2px 2px;
text-align: center;
margin: 6px 0;
border: none;
}
table {
width: 100%;
background-color: #454545;
font-weight: 500;
border-collapse: separate;
border-spacing: 0.3em 1.1em;
color: #fff;
border: 0;
}
p {
font-size: 1.2vw;
}
.boxes {
padding-top: 40px;
padding-left: 30px;
padding-right: 5%;
min-width: 200px;
float: left;
display: inline-block;
}
#line {
border-bottom: solid 1px #CCC;
margin-top: 0px;
padding-top: 15px;
}
.infobox {
float: left;
margin: 0;
box-shadow: 1px 2px 4px rgba(0, 0, 0, .5);
color: #454545;
}
.infobox1 {
float: left;
min-height: 150px;
min-width: 100%;
margin: 0;
}
.infobox2 {
float: left;
min-height: 150px;
min-width: 49%;
margin: 0 0.5%;
//padding: 18px 0;
}
.infobox3 {
float: left;
min-height: 150px;
min-width: 32.33%;
margin: 0 0.5%;
//padding: 18px 0;
}
.infobox4 {
float: left;
//min-height:150px;
min-width: 23.9%;
margin: 0 0.5%;
//padding: 18px 0;
}
.infobox5 {
float: left;
min-height: 150px;
min-width: 32.33%;
margin: 0 0.5% 0.7%;
//padding: 18px 0;
}
div.leftBox {
float: left;
width: 60%;
margin: 15px 0 0 25px;
font-size: 1.1vw;
}
div.rightBox {
float: left;
width: 60%;
margin: 15px 0 0 25px;
font-size: 1.1vw;
}
.infocontentheader {
//text-align: center;
line-height: 2.8;
//color: #fff;
vertical-align: middle;
height: 100%;
float: left;
width: 25%;
}
.infocontent {
text-align: center;
color: #fff;
width: 50%;
float: left;
}
div#facebook.infocontentheader {
background-color: #3c5999;
}
div#facebook.infobox img {
display: block;
margin: 0 auto 0 auto;
}
p#sTitle {
font-weight: 900;
font-size: 1.5vw;
}
p#bTitle {
//font-weight: 900;
font-size: 1.2vw;
}
p#facebook_spend,
p#youtube_spend,
p#search_spend,
p#programmatic_spend,
p#instagram_spend,
p#twitter_spend {
font-weight: 900;
font-size: 1.3em;
margin: 10px 0 0 20px;
}
p#facebook_budget,
p#youtube_budget,
p#search_budget,
p#programmatic_budget,
p#instagram_budget,
p#twitter_budget {
font-size: 1.2em;
margin: 10px 0 0 20px;
}
div#twitter.infocontentheader {
background-color: #1da1f2;
}
div#twitter.infobox img {
display: block;
margin: 0 auto 0 auto;
}
div#programmatic.infocontentheader {
background-color: #a15aa0;
}
div#display.parentbox {
background-color: #b3b3b3;
color: #fff;
}
div#video.parentbox {
background-color: #999999;
color: #fff;
}
div#mixed.parentbox {
background-color: #c1c1c1;
color: #fff;
}
#programmatic div.infocontentheader {
color: #fff;
}
div#programmatic.infobox img {
display: block;
margin: 0 auto 0 auto;
}
div#programmatic_value.infocontent {
color: #000;
}
div#youtube.infocontentheader {
background-color: #ff0102;
}
div#youtube.infobox img {
display: block;
margin: 0 auto 0 auto;
}
div#search.infocontentheader {
background-color: #cac9c2;
}
div#search.infobox img {
display: block;
margin: 10% auto 0 auto;
}
div#instagram.infobox {
background-color: #fff;
}
div#instagram.infobox img {
display: block;
margin: 10% auto 0 auto;
}
.hidden {
display: none;
}
#parent_div_1 {
width: 50%;
min-height: 150px;
background-color: #757476;
margin-right: 0px;
float: left;
}
#parent_div_2 {
width: 50%;
min-height: 150px;
background-color: #8D8D8D;
margin-right: 0px;
float: left;
}
.parentbox {
width: 33.33%;
min-height: 150px;
/*background-color: #8D8D8D;*/
margin-right: 0px;
float: left;
}
.parentbox1 {
width: 100%;
min-height: 150px;
margin-right: 0px;
float: left;
}
.parentbox2 {
width: 50%;
min-height: 150px;
margin-right: 0px;
float: left;
}
.parentbox3 {
width: 33.33%;
min-height: 150px;
margin-right: 0px;
float: left;
}
.child_div_1 {
margin-top: 50px;
margin-left: 15%;
margin-bottom: 0px;
text-align: left;
}
.child_div_2 {
margin-left: 15%;
margin-top: 10px;
margin-bottom: 40px;
text-align: left;
}
.child_budget {
margin-top: 10px;
margin-bottom: 40px;
padding-left: 15%;
text-align: left;
float: left;
}
.child_spend {
margin-top: 10px;
margin-bottom: 40px;
padding-right: 15%;
text-align: left;
float: right;
}
.child_title {
margin-top: 50px;
margin-bottom: 0px;
text-align: center;
}
.child_budget_number {
padding-right: 20%;
}
.child_spend_number {
padding-left: 20%;
}
.boxbox {
display: table;
width: 99.8%;
height: 160px;
font-size: 1.1vw;
}
.boxbox {
float: left;
display: table;
width: 99.8%;
height: 180px;
}
.boxbox>.col-lg-6 {
display: table-cell;
vertical-align: middle;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div id="wrapper2" style="height:160px;">
<div class="infobox infobox5" id="platform1">
<div class="boxbox">
<div class="col-lg-6" style="background-color: #3c5999; min-width: 50px;">
<img src="">
</div>
<div class="col-lg-6" style="float: left;">
<div class="container">
<div id="sTitle">value1<br>
<div id="platform1_value1">353</div>
</div>
<div id="bTitle">value2<br>
<div id="platform1_value2">1,634</div>
</div>
</div>
</div>
</div>
</div>
<div class="infobox hidden" id="platform6">
<div class="boxbox" style="color: rgb(255, 255, 255);">
<div class="col-lg-6" style="background-color: #3c5999; min-width: 50px;">
<img src="">
</div>
<div class="col-lg-6" style="float: left;">
<div class="container">
<div id="sTitle">value1<br>
<div id="platform6_value1"></div>
</div>
<div id="bTitle">value2<br>
<div id="platform6_value2"></div>
</div>
</div>
</div>
</div>
</div>
<div class="infobox infobox5" id="platform5">
<div class="boxbox" >
<div class="col-lg-6" style="background-color: #a15aa0; min-width: 50px;">
<img src="">
</div>
<div class="col-lg-6" style="float: left;">
<div class="container">
<div id="sTitle">value1<br>
<div id="platform5_value1">706</div>
</div>
<div id="bTitle">value2<br>
<div id="platform5_value2"></div>
</div>
</div>
</div>
</div>
</div>
<div class="infobox infobox5" id="platform3">
<div class="boxbox" id="platform3" >
<div class="col-lg-6" style="background-color: #ff0102; min-width: 50px;">
<img src="">
</div>
<div class="col-lg-6" style="float: left;">
<div class="container">
<div id="sTitle">value1<br>
<div id="platform3_value1">404</div>
</div>
<div id="bTitle">value2<br>
<div id="platform3_value2"></div>
</div>
</div>
</div>
</div>
</div>
<div class="infobox infobox5" id="platform4">
<div class="boxbox">
<div class="col-lg-6" style="background-color: #cac9c2; min-width: 50px;">
<img src="">
</div>
<div class="col-lg-6" style="float: left;">
<div class="container">
<div id="sTitle">value1<br>
<div id="platform4_value1">353</div>
</div>
<div id="bTitle">value2<br>
<div id="platform4_value2"></div>
</div>
</div>
</div>
</div>
</div>
<div class="infobox infobox5" id="platform2">
<div class="boxbox" id="platform2" >
<div class="col-lg-6" style="background-color: #8a3ab9; min-width: 50px;">
<img src="">
</div>
<div class="col-lg-6" style="float: left;">
<div class="container">
<div id="sTitle">value1<br>
<div id="platform2_value1">404</div>
</div>
<div id="bTitle">value2<br>
<div id="platform2_value2">6,364</div>
</div>
</div>
</div>
</div>
</div>
</div>
Use: element.eq(n); where n is the index value of the element

Categories