How to make the prev button remove activity from progress - javascript

How can I make the prev button remove activity from progress:
var currentTab = 0; // Current tab is set to be the first tab (0)
showTab(currentTab); // Display the current tab
function showTab(n) {
// This function will display the specified tab of the form...
var x = document.getElementsByClassName("tab");
x[n].style.display = "block";
//... and fix the Previous/Next buttons:
if (n == 0) {
document.getElementById("prevBtn").style.display = "none";
} else {
document.getElementById("prevBtn").style.display = "inline";
}
if (n == (x.length - 1)) {
document.getElementById("nextBtn").innerHTML = "Submit";
} else {
document.getElementById("nextBtn").innerHTML = "Continue";
}
//... and run a function that will display the correct step indicator:
fixStepIndicator(n)
}
function nextPrev(n) {
// This function will figure out which tab to display
var x = document.getElementsByClassName("tab");
// Exit the function if any field in the current tab is invalid:
if (n == 1 && !validateForm()) return false;
// Hide the current tab:
x[currentTab].style.display = "none";
// Increase or decrease the current tab by 1:
currentTab = currentTab + n;
// if you have reached the end of the form...
if (currentTab >= x.length) {
// ... the form gets submitted:
document.getElementById("regForm").submit();
return false;
}
// Otherwise, display the correct tab:
showTab(currentTab);
}
function removeElementsByClass(className) {
const elements = document.getElementsByClassName(className);
while (elements.length > 0) {
elements[0].parentNode.removeChild(elements[0]);
}
}
function validateForm() {
removeElementsByClass("validation-message");
// This function deals with validation of the form fields
var x, y, i, valid = true;
x = document.getElementsByClassName("tab");
// y = x[currentTab].getElementsByTagName("input");
y = x[currentTab].getElementsByClassName("required");
// A loop that checks every input field in the current tab:
for (i = 0; i < y.length; i++) {
// If a field is empty...
if (y[i].value == "") {
// add an "invalid" class to the field:
y[i].className += " invalid";
// and set the current valid status to false
valid = false;
if (y[i].classList.contains("signature")) {
alert("You should add you signature then click the button 'Add signature'")
}
}
}
//Validate Password
var passwordField = x[currentTab].getElementsByClassName("passwordfield");
if (passwordField.length) {
if (passwordField[0].value.length < 8) {
passwordField[0].className += " invalid";
passwordField[0].insertAdjacentHTML('afterend', '<span class="validation-message">Use 8 or more characters for your password.</span>');
valid = false;
}
if (passwordField[0].value.length > 50) {
passwordField[0].className += " invalid";
passwordField[0].insertAdjacentHTML('afterend', '<span class="validation-message">Use less than 50 characters for your password.</span>');
valid = false;
}
if (passwordField[0].value != passwordField[1].value) {
passwordField[1].className += " invalid";
passwordField[1].insertAdjacentHTML('afterend', '<span class="validation-message">The two passwords entered do not match. Please try again.</span>');
valid = false;
}
}
//Validate Password
var all_alphanumric = x[currentTab].getElementsByClassName("alphanumric");
if (all_alphanumric.length) {
// var letterNumber = /^[0-9a-zA-Z]+$/;
var letterNumber = /^[a-z\d\-_\s]+$/i;
for (j = 0; j < all_alphanumric.length; j++) {
if (all_alphanumric[j].value.length && !(all_alphanumric[j].value.match(letterNumber))) {
all_alphanumric[j].className += " invalid";
all_alphanumric[j].insertAdjacentHTML('afterend', '<span class="validation-message">Sorry, but only letters (Aa-Zz) and numbers (0-9) are allowed.</span>');
valid = false;
}
}
}
//Validate Mobile
var all_mobiles = x[currentTab].getElementsByClassName("mobile_number");
if (all_mobiles.length) {
var letterNumber = /^[\+]?[(]?[0-9]{3}[)]?[-\s\.]?[0-9]{3}[-\s\.]?[0-9]{4,6}$/im;
for (k = 0; k < all_mobiles.length; k++) {
if (all_mobiles[k].value.length && !(all_mobiles[k].value.match(letterNumber))) {
all_mobiles[k].className += " invalid";
all_mobiles[k].insertAdjacentHTML('afterend', '<span class="validation-message">Please use a valid mobile number.</span>');
valid = false;
}
}
}
//Validate Email
var all_mails = x[currentTab].getElementsByClassName("email_address");
if (all_mails.length) {
var re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
for (s = 0; s < all_mails.length; s++) {
if (all_mails[s].value.length && !(re.test(all_mails[s].value))) {
all_mails[s].className += " invalid";
all_mails[s].insertAdjacentHTML('afterend', '<span class="validation-message">Please use a valid email adress.</span>');
valid = false;
}
}
}
// If the valid status is true, mark the step as finished and valid:
if (valid) {
document.getElementsByClassName("progtrckr-todo")[currentTab].className += " progtrckr-done";
}
return valid; // return the valid status
}
function fixStepIndicator(n) {
// This function removes the "active" class of all steps...
var i, x = document.getElementsByClassName("progtrckr-todo");
for (i = 0; i < x.length; i++) {
x[i].className = x[i].className.replace(" active", "");
}
//... and adds the "active" class on the current step:
x[n].className += " active";
}
/* Start CSS FOR Multi Steps */
.multiSteps {
margin: 90px 0;
}
.filter-multi {
display: flex;
width: 339px;
height: 57px;
margin: auto;
outline: 1px solid #707070;
border-radius: 42px;
overflow: hidden;
}
.filter-multi div {
width: 50%;
display: flex;
align-items: center;
justify-content: center;
height: 100%;
cursor: pointer;
}
.filter-multi div h2 {
color: #393C41;
font-size: 21px;
font-family: "HelveticaNeue-bold";
letter-spacing: -1.16px;
}
.filter-multi .frist h2 {
color: #fff;
}
.filter-multi .frist {
background: #27BA5A;
border-radius: 0 42px 42px 0;
}
/* Style the form */
#regForm {
background-color: #ffffff;
margin-top: 120px;
margin-left: auto;
width: 70%;
min-width: 300px;
}
/* Mark input boxes that gets an error on validation: */
#regForm input.invalid {
background-color: #ffdddd;
}
/* Hide all steps by default: */
#regForm .tab {
display: none;
}
/* Make circles that indicate the steps of the form: */
#regForm .step {
height: 15px;
width: 15px;
margin: 0 2px;
background-color: #bbbbbb;
border: none;
border-radius: 50%;
display: inline-block;
opacity: 0.5;
}
/* Mark the active step: */
#regForm .step.active {
opacity: 1;
}
/* Mark the steps that are finished and valid: */
#regForm .step.finish {
background-color: #27BA5A;
border-radius: 3px;
}
#regForm button {
background-color: #27BA5A;
color: #ffffff;
border: none;
padding: 10px 20px;
font-size: 17px;
border-radius: 3px;
cursor: pointer;
height: 41px;
width: 156px;
margin-top: 30px;
}
#regForm #prevBtn {
background-color: #bbbbbb;
}
/* Progress Tracker v2 */
ol.progtrckr {
margin: 0;
padding: 0;
list-style-type: none;
}
ol.progtrckr li {
display: inline-block;
text-align: center;
line-height: 3em;
}
ol.progtrckr[data-progtrckr-steps="2"] li {
width: 49%;
}
ol.progtrckr[data-progtrckr-steps="3"] li {
width: 33%;
}
ol.progtrckr[data-progtrckr-steps="4"] li {
width: 24%;
}
ol.progtrckr[data-progtrckr-steps="5"] li {
width: 19%;
}
ol.progtrckr li.progtrckr-todo {
color: silver;
border-bottom: 11px solid #27BA5A;
opacity: 1;
}
ol.progtrckr li.progtrckr-done {
color: black;
border-bottom: 11px solid #27BA5A;
opacity: 1 !important;
}
ol.progtrckr li:after {
content: "\00a0\00a0";
}
ol.progtrckr li:before {
position: relative;
font-size: 40px;
font-family: "HelveticaNeue-bold";
left: 50%;
transform: translate(-50%, 50%);
height: 75px;
width: 75px;
}
ol.progtrckr li.progtrckr-todo:before {
content: "1";
height: 75px;
width: 75px;
line-height: 1.2em;
border: none;
border-radius: 50%;
bottom: -35px;
left: 35%;
display: flex;
align-items: center;
justify-content: center;
font-size: 40px;
font-family: "HelveticaNeue-bold";
color: #27BA5A;
background-color: white;
border: 3px solid #27BA5A;
}
ol.progtrckr li.progtrckr-todo:nth-child(1):before {
content: "1";
}
ol.progtrckr li.progtrckr-todo:nth-child(2):before {
content: "2";
}
ol.progtrckr li.progtrckr-todo:nth-child(3):before {
content: "3";
}
ol.progtrckr li.progtrckr-todo:nth-child(4):before {
content: "4";
}
ol.progtrckr li.progtrckr-todo:nth-child(5):before {
content: "5";
}
ol.progtrckr li.progtrckr-done:before {
content: "\2713";
color: white;
background-color: #27BA5A;
height: 75px;
width: 75px;
line-height: 1.2em;
border: none;
border-radius: 50%;
bottom: -35px;
left: 35%;
transform: translate(-50%, 50%);
display: flex;
align-items: center;
justify-content: center;
font-size: 40px;
font-family: "HelveticaNeue-bold";
}
ol.progtrckr {
display: table;
list-style-type: none;
margin: 0;
padding: 0;
table-layout: fixed;
width: 100%;
}
ol.progtrckr li {
display: table-cell;
text-align: center;
line-height: 2.9;
font-size: 12px;
font-weight: 700;
}
ol.progtrckr li.active {
opacity: 1 !important;
}
.bolts-step {
display: none;
}
/* Mark the active step: */
.step.active {
opacity: 1;
}
.progtrckr span {
font-size: 18px;
display: block;
width: 166px;
line-height: 1;
text-align: center;
position: absolute;
left: 125px;
bottom: -35px;
color: #393C41;
font-family: "HelveticaNeue-bold";
width: max-content;
}
.progtrckr li {
position: relative;
}
ol.progtrckr li.progtrckr-done:nth-child(1):before {
content: "1";
}
ol.progtrckr li.progtrckr-done:nth-child(2):before {
content: "2";
}
ol.progtrckr li.progtrckr-done:nth-child(3):before {
content: "3";
}
ol.progtrckr li.progtrckr-done:nth-child(4):before {
content: "4";
}
ol.progtrckr li.progtrckr-done:nth-child(5):before {
content: "5";
}
.multiSteps .title-regform {
font-size: 36px;
font-family: "HelveticaNeue-bold";
letter-spacing: -1.98px;
color: #393C41;
margin-bottom: 50px;
}
.multiSteps .grid-towCloman {
display: grid;
grid-template-columns: 1fr 1fr;
grid-gap: 45px;
margin-bottom: 30px;
}
#regForm .form-erea label {
font-size: 12px;
font-family: "HelveticaNeue-R";
letter-spacing: 0px;
color: #393C41;
margin-bottom: 7px;
display: block;
}
#regForm .form-erea ::placeholder {
font-size: 12px;
font-family: "HelveticaNeue-R";
color: #393C41;
}
#regForm .form-erea textarea,
#regForm .form-erea select,
#regForm .form-erea input {
padding: 10px 15px;
width: 100%;
border: 1px solid #D8D9D9;
height: 41px;
}
#regForm .form-erea textarea {
height: 133px;
}
#regForm .grid-diffCloman {
display: grid;
grid-template-columns: 8% 87%;
grid-gap: 41px;
margin-bottom: 30px;
}
#regForm .grid-diffCloman .form-erea select {
text-align: center;
}
#regForm .form-erea select {
-webkit-appearance: none;
-moz-appearance: none;
background: transparent;
background-image: url("data:image/svg+xml;utf8,<svg fill='black' height='24' viewBox='0 0 24 24' width='24' xmlns='http://www.w3.org/2000/svg'><path d='M7 10l5 5 5-5z'/><path d='M0 0h24v24H0z' fill='none'/></svg>");
background-repeat: no-repeat;
background-position-x: 98%;
background-position-y: 7px;
}
.grid-fourCloman {
display: grid;
grid-template-columns: 1fr 1fr 1fr 1fr;
grid-gap: 26px;
margin-bottom: 30px;
}
.checkbox-form {
display: flex;
align-items: center;
}
.checkbox-form label {
margin-left: 15px;
}
/* END CSS FOR Multi Steps */
<!DOCTYPE html>
<html>
<head>
<title>Book Now</title>
<meta charset="utf-8">
</head>
<body>
<!-- Start Multi Steps-->
<section class="multiSteps">
<div class="container">
<div class="row">
<div class="col-md-12">
<div class="filter-multi">
<div class="frist">
<h2>Australia</h2>
</div>
<div class="second">
<h2>International</h2>
</div>
</div>
</div>
<div class="col-md-12">
<div class="progreess-multi-step">
<div class="ling-green"></div>
<ol class="progtrckr progress" data-progtrckr-steps="9">
<li class="step progtrckr-todo ">
<span>Shipment details</span>
</li>
<li class=" step progtrckr-todo ">
<span>Quote</span>
</li>
<li class=" step progtrckr-todo">
<span>Address</span>
</li>
<li class="step progtrckr-todo">
<span>Summary</span>
</li>
<li class="step progtrckr-todo">
<span>Payment</span>
</li>
</ol>
</div>
<form id="regForm" action="">
<!-- One "tab" for each step in the form: -->
<div class="tab" style="display: block;">
<h2 class="title-regform">01 Shipment details</h2>
<div class="grid-towCloman">
<div class="form-erea">
<label for=" ">Pick-up Date</label>
<input placeholder="Pick-up Date" oninput="this.className = ''">
</div>
<div class="form-erea">
<label for="">Pick-up Time</label>
<input placeholder="12:00pm" oninput="this.className = ''">
</div>
</div>
<div class="grid-towCloman">
<div class="form-erea">
<label for="">Service Type</label>
<select name="" id="">
<option value="Express">Express</option>
<option value="Express">Express</option>
</select>
</div>
<div class="form-erea">
</div>
</div>
<div class="grid-diffCloman">
<div class="form-erea">
<label for="">Quantity</label>
<select name="" id="">
<option value="01">01</option>
<option value="02">02</option>
</select>
</div>
<div class="form-erea">
<label for="">Description</label>
<textarea name="" id="" rows="10" placeholder="Description"></textarea>
</div>
</div>
<div class="grid-fourCloman">
<div class="form-erea">
<label for=" ">Weight</label>
<input placeholder="Weight (KG)" oninput="this.className = ''">
</div>
<div class="form-erea">
<label for="">Width</label>
<input placeholder="Width (MM)" oninput="this.className = ''">
</div>
<div class="form-erea">
<label for=" ">Length</label>
<input placeholder="Length (MM)" oninput="this.className = ''">
</div>
<div class="form-erea">
<label for="">Height</label>
<input placeholder="Height (MM)" oninput="this.className = ''">
</div>
</div>
<div class="grid-oneCloman">
<div class="checkbox-form">
<input type="checkbox">
<label for="">Save this information for next time</label>
</div>
</div>
</div>
<div class="tab">
<h2 class="title-regform">02 Destination </h2>
</div>
<div class="tab">
<h2 class="title-regform"> </h2>
<div class="form-erea"><input placeholder="dd" oninput="this.className = ''"></div>
<div class="form-erea"><input placeholder="mm" oninput="this.className = ''"></div>
<div class="form-erea"><input placeholder="yyyy" oninput="this.className = ''"></div>
</div>
<div class="tab">
<h2 class="title-regform"> </h2>
<div class="form-erea"><input placeholder="Username..." oninput="this.className = ''"></div>
<div class="form-erea"><input placeholder="Password..." oninput="this.className = ''"></div>
</div>
<div style="overflow:auto;">
<div style="">
<button type="button" id="prevBtn" onclick="nextPrev(-1)">Previous</button>
<button type="button" id="nextBtn" onclick="nextPrev(1)">Next</button>
</div>
</div>
</form>
</div>
</div>
</div>
</section>
</body>
</html>

Related

This last step on my Note app... When I click on view more modal window is created, but the wrong one

'use strict';
// Select all elements needed for this task (querySelector)
const form = document.querySelector('.form');
const input = document.querySelector('.input__text');
let container = document.querySelector('.notes-container');
const button = document.querySelector('.btn');
const noteDiv = document.querySelector('.note');
let modal = document.querySelector('.modal');
const overlay = document.querySelector('.overlay');
const btnClose = document.querySelectorAll('.close-modal');
const btnView = document.querySelector('.btn-view');
let noteCount = 0;
// Create function that reads when the button is clicked on form
form.addEventListener('submit', function (e) {
e.preventDefault();
// if input filed is empty note will not be added!
if (!input.value == '') {
// Every time i click on button, notCount is incremented by one. Then that count i store and use to count number of note
if (button.click) noteCount++;
// Creating div element where notes will go
const divNotes = document.createElement('div');
// Adding class to that div element
divNotes.classList.add('note');
// Inserting HTML content into created div
const createdNote = (divNotes.innerHTML += `
<h4 class="note__heading">Note ${noteCount}</h4>
<p class="note__text">${input.value}</p>
<button class="btn btn-view">View Detail</button>
`);
container.appendChild(divNotes);
//
container.addEventListener('click', function (e) {
if (!e.target.classList.contains('btn-view')) {
return;
}
modal.classList.remove('hidden');
overlay.classList.remove('hidden');
modal.innerHTML = `<h4 class="note__heading">Note ${noteCount}</h4>
<p class="note__text">${input.value}</p>
<button class="close-modal">X</button>
`;
});
modal.addEventListener('click', function (e) {
if (!e.target.classList.contains('close-modal')) {
return;
}
modal.classList.add('hidden');
overlay.classList.add('hidden');
});
}
});
html {
margin: 0;
padding: 0;
font-family: 'Courier New', Courier, monospace;
box-sizing: border-box;
}
body {
display: grid;
place-items: center;
}
.container__app {
text-align: center;
}
h1 {
font-size: 4rem;
font-weight: 100;
}
h3 {
font-size: 2rem;
color: green;
margin-top: -40px;
}
.input__text {
width: 1310px;
height: 50px;
margin-bottom: 15px;
padding: 10px;
font-size: 16px;
resize: none;
}
label {
bottom: 36px;
padding: 3px;
vertical-align: top;
font-size: 25px;
font-weight: 600;
}
.btn-green {
color: white;
background-color: green;
width: 100px;
height: 35px;
border-radius: 5px;
border: none;
}
.btn-span {
margin-top: 15px;
}
.btn-green:active {
transform: translateY(4px);
}
.notes-container {
margin: auto;
padding: 25px;
display: grid;
grid-template-columns: repeat(auto-fit, minmax(500px, 1fr));
grid-gap: 1.5rem;
}
.note {
border: 1px solid gray;
padding-bottom: 18px;
margin-top: 15px;
}
.note__text {
overflow: hidden;
max-height: 7rem;
-webkit-box-orient: vertical;
display: -webkit-box;
text-overflow: ellipsis;
-webkit-line-clamp: 4;
word-wrap: break-word;
padding: 0 20px 4px 20px;
}
h4 {
font-size: 25px;
}
p {
font-size: 20px;
}
.btn-view {
color: white;
background-color: rgb(24, 113, 197);
width: 100px;
height: 35px;
border-radius: 5px;
border: none;
}
.btn-view:active {
transform: translateY(4px);
}
.modal {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 70%;
border-radius: 5px;
background-color: white;
padding: 6rem;
box-shadow: 0 3rem 5rem rgba(0 0 0 0.3);
z-index: 10;
}
.overlay {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.6);
backdrop-filter: blur(3px);
z-index: 5;
}
.hidden {
display: none;
}
.close-modal {
position: absolute;
top: 1.2rem;
right: 2rem;
font-size: 2rem;
color: #333;
cursor: pointer;
border: none;
background: 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" />
<title>Note Taker App</title>
<link rel="stylesheet" href="style.css" />
<script src="script.js" defer></script>
</head>
<body>
<div class="container__app">
<h1>Note Taker</h1>
<h3>Add a new note:</h3>
<div class="input__field">
<form class="form">
<label class="input__text-name">Note: </label>
<textarea
rows="5"
cols=""
class="input__text"
placeholder="Write your note here"
></textarea>
<label for="submit"></label><br />
<button class="btn btn-green" type="submit">Add Note</button>
</form>
</div>
<div class="modal hidden">
<button class="close-modal">X</button>
</div>
<div class="overlay hidden"></div>
<div class="notes-container">
<!-- <div class="note">
<h4 class="note__heading">Note1</h4>
<p class="note__text">
MY note text
</p>
<div class="note__btn">
<button class="btn btn-view">View Detail</button>
</div>
</div> -->
</div>
</div>
</body>
</html>
Im new to programming, please help. I finished almost everything except last step. This is the problem: when I press button view more (it should create modal window related to that note and button). Thing is that everything is working fine when you press buttons in order (like note1, note2, note3), but if you press 6th button and then the first one, only last element will be created. If someone can explain me how this works. https://codepen.io/Niksani/pen/GROXGyN
const form = document.querySelector('.form');
const input = document.querySelector('.input__text');
let container = document.querySelector('.notes-container');
const button = document.querySelector('.btn');
const noteDiv = document.querySelector('.note');
let modal = document.querySelector('.modal');
const overlay = document.querySelector('.overlay');
const btnClose = document.querySelectorAll('.close-modal');
const btnView = document.querySelector('.btn-view');
let noteCount = 0;
form.addEventListener('submit', function (e) {
e.preventDefault();
if (!input.value == '') {
and use to count number of note
if (button.click) noteCount++;
const divNotes = document.createElement('div');
divNotes.classList.add('note');
const createdNote = (divNotes.innerHTML += `
<h4 class="note__heading">Note ${noteCount}</h4>
<p class="note__text">${input.value}</p>
<button class="btn btn-view">View Detail</button>
`);
container.appendChild(divNotes);
//
container.addEventListener('click', function (e) {
if (!e.target.classList.contains('btn-view')) {
return;
}
modal.classList.remove('hidden');
overlay.classList.remove('hidden');
modal.innerHTML = `<h4 class="note__heading">Note ${noteCount}</h4>
<p class="note__text">${input.value}</p>
<button class="close-modal">X</button>
`;
});
modal.addEventListener('click', function (e) {
if (!e.target.classList.contains('close-modal')) {
return;
}
modal.classList.add('hidden');
overlay.classList.add('hidden');
});
}
});
'use strict';
// Select all elements needed for this task (querySelector)
const form = document.querySelector('.form');
const input = document.querySelector('.input__text');
let container = document.querySelector('.notes-container');
const button = document.querySelector('.btn');
const noteDiv = document.querySelector('.note');
let modal = document.querySelector('.modal');
const overlay = document.querySelector('.overlay');
const btnClose = document.querySelectorAll('.close-modal');
const btnView = document.querySelector('.btn-view');
let noteCount = 0;
// Create function that reads when the button is clicked on form
form.addEventListener('submit', function (e) {
e.preventDefault();
// if input filed is empty note will not be added!
if (!input.value == '') {
// Every time i click on button, notCount is incremented by one. Then that count i store and use to count number of note
if (button.click) noteCount++;
// Creating div element where notes will go
const divNotes = document.createElement('div');
// Adding class to that div element
divNotes.classList.add('note');
// Inserting HTML content into created div
const createdNote = (divNotes.innerHTML += `
<h4 class="note__heading">Note ${noteCount}</h4>
<p id='note${noteCount}' class="note__text">${input.value}</p>
<button class="btn btn-view" value='${noteCount}'>View Detail</button>
`);
container.appendChild(divNotes);
//
container.addEventListener('click', function (e) {
if (!e.target.classList.contains('btn-view')) {
return;
}
let showNote = '';
showNote = e.target.value;
let noteText = document.getElementById(`note${showNote}`).innerHTML;
modal.classList.remove('hidden');
overlay.classList.remove('hidden');
modal.innerHTML = `<h4 class="note__heading">Note ${showNote}</h4>
<p class="note__text">${noteText}</p>
<button class="close-modal">X</button>
`;
});
modal.addEventListener('click', function (e) {
if (!e.target.classList.contains('close-modal')) {
return;
}
modal.classList.add('hidden');
overlay.classList.add('hidden');
});
}
});
html {
margin: 0;
padding: 0;
font-family: 'Courier New', Courier, monospace;
box-sizing: border-box;
}
body {
display: grid;
place-items: center;
}
.container__app {
text-align: center;
}
h1 {
font-size: 4rem;
font-weight: 100;
}
h3 {
font-size: 2rem;
color: green;
margin-top: -40px;
}
.input__text {
width: 1310px;
height: 50px;
margin-bottom: 15px;
padding: 10px;
font-size: 16px;
resize: none;
}
label {
bottom: 36px;
padding: 3px;
vertical-align: top;
font-size: 25px;
font-weight: 600;
}
.btn-green {
color: white;
background-color: green;
width: 100px;
height: 35px;
border-radius: 5px;
border: none;
}
.btn-span {
margin-top: 15px;
}
.btn-green:active {
transform: translateY(4px);
}
.notes-container {
margin: auto;
padding: 25px;
display: grid;
grid-template-columns: repeat(auto-fit, minmax(500px, 1fr));
grid-gap: 1.5rem;
}
.note {
border: 1px solid gray;
padding-bottom: 18px;
margin-top: 15px;
}
.note__text {
overflow: hidden;
max-height: 7rem;
-webkit-box-orient: vertical;
display: -webkit-box;
text-overflow: ellipsis;
-webkit-line-clamp: 4;
word-wrap: break-word;
padding: 0 20px 4px 20px;
}
h4 {
font-size: 25px;
}
p {
font-size: 20px;
}
.btn-view {
color: white;
background-color: rgb(24, 113, 197);
width: 100px;
height: 35px;
border-radius: 5px;
border: none;
}
.btn-view:active {
transform: translateY(4px);
}
.modal {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 70%;
border-radius: 5px;
background-color: white;
padding: 6rem;
box-shadow: 0 3rem 5rem rgba(0 0 0 0.3);
z-index: 10;
}
.overlay {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.6);
backdrop-filter: blur(3px);
z-index: 5;
}
.hidden {
display: none;
}
.close-modal {
position: absolute;
top: 1.2rem;
right: 2rem;
font-size: 2rem;
color: #333;
cursor: pointer;
border: none;
background: none;
}
<div class="container__app">
<h1>Note Taker</h1>
<h3>Add a new note:</h3>
<div class="input__field">
<form class="form">
<label class="input__text-name">Note: </label>
<textarea
rows="5"
cols=""
class="input__text"
placeholder="Write your note here"
></textarea>
<label for="submit"></label><br />
<button class="btn btn-green" type="submit">Add Note</button>
</form>
</div>
<div class="modal hidden">
<button class="close-modal">X</button>
</div>
<div class="overlay hidden"></div>
<div class="notes-container">
<!-- <div class="note">
<h4 class="note__heading">Note1</h4>
<p class="note__text">
MY note text
</p>
<div class="note__btn">
<button class="btn btn-view">View Detail</button>
</div>
</div> -->
</div>
</div>
check out the new event listener for your btn.click event...I am determining which note to show by getting the button value attribute that was added to the string literal....I am using that value to get the text of the note by giving the p an id and referencing that....I believe this gives you what you are looking for

Can someone help me,and fix the animation problem in my javascript?

I'm working on a registration form,and I have a problem with an input field animation,I want to change the color of the input field bottom border to red and the icons color,when the user enter data,which isn't correct for the requirements.This is halfly working with the icons,because they doesn't have javascript animation function,but not working with the fields border colors.
So,when the user click on the input field,I want to play the animation,and make the border green,when the user type something like an "a" character,then the border be red,and if the data match with all of the requirements,then be the border green again.
I think the problem is somewhere in the animation script,at the 271 line,because if I delete that,the border color change start working well,I think the two javascript conflict each other,it's just a bit hint for you. I don't have too much experience in web development.
Here is the code: https://jsfiddle.net/hgf2346v/
function Showfunction() {
var eye = document.getElementById("eye");
var eye2 = document.getElementById("eye2");
var pass = document.getElementById("pass");
if (pass.type === "password") {
pass.type = "text";
eye.style.display = "none";
eye2.style.display = "block";
} else {
pass.type = "password";
eye2.style.display = "none";
eye.style.display = "block";
}
}
function hiddenscript() {
var eye = document.getElementById("eye");
eye.style.display = "block";
}
$(document).ready(function() {
// set initially button state hidden
// use keyup event on email field
$("#email").keyup(function() {
if (validateEmail()) {
// if the email is validated
// set input email border green
$('#inputemail').css('border-bottom', 'solid 2px #38d39f');
$('#iconmail').css('color', '#38d39f');
$("#emailMsg").html("<p class='text-danger'></p>");
$(':input[type="submit"]').prop('disabled', false);
// and set label
} else {
// if the email is not validated
// set border red
$('#inputemail').css('border-bottom', 'solid 2px #e50914');
$('#iconmail').css('color', '#e50914');
$("#emailMsg").html("<p class='text-danger'>Enter valid email.</p>");
$(':input[type="submit"]').prop('disabled', true);
}
});
$("#pass").keyup(function() {
// check
if (validatePassword()) {
// set input password border green
$('#inputpass').css('border-bottom', 'solid 2px #38d39f');
$('#iconpass').css('color', '#38d39f');
$("#passMsg").html("<p class='text-danger'></p>");
$(':input[type="submit"]').prop('disabled', false);
//set passMsg
} else {
$('#inputpass').css('border-bottom', 'solid 2px #e50914');
$('#iconpass').css('color', '#e50914');
$("#passMsg").html("<p class='text-danger'>Password must contain at least 1 digit,<br>and need to contain at least 8 character.</p>");
$(':input[type="submit"]').prop('disabled', true);
}
});
$("#firstName").keyup(function() {
// check
if (validateFirstName()) {
// set input password border green
$('#inputfirstname').css('border-bottom', 'solid 2px #38d39f');
$('#iconfirstname').css('color', '#38d39f');
$("#firstMsg").html("<p class='text-danger'></p>");
$(':input[type="submit"]').prop('disabled', false);
//set passMsg
} else {
$('#inputfirstname').css('border-bottom', 'solid 2px #e50914');
$('#iconfirstname').css('color', '#e50914');
$("#firstMsg").html("<p class='text-danger'>The first name must be at least 3 character long.</p>");
$(':input[type="submit"]').prop('disabled', true);
}
});
$("#lastName").keyup(function() {
// check
if (validateLastName()) {
// set input password border green
$('#inputlastname').css('border-bottom', 'solid 2px #38d39f');
$('#iconlastname').css('color', '#38d39f');
$("#lastMsg").html("<p class='text-danger'></p>");
$(':input[type="submit"]').prop('disabled', false);
//set passMsg
} else {
$('#inputlastname').css('border-bottom', 'solid 2px #e50914');
$('#iconlastname').css('color', '#e50914');
$("#lastMsg").html("<p class='text-danger'>The last name must be at least 3 character long.</p>");
$(':input[type="submit"]').prop('disabled', true);
}
});
});
function validateEmail() {
// get value of input email
var email = $("#email").val();
// use reular expression
var reg = /^\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*$/
if (reg.test(email)) {
return true;
} else {
return false;
}
}
function validatePassword() {
var pass = $("#pass").val();
var reg = /^(?=.*\d)(?=.*[a-z])[0-9a-zA-Z]{8,}$/
if (reg.test(pass)) {
return true;
} else {
return false;
}
}
function validateFirstName() {
//get input password value
var first = $("#firstName").val();
// check it s length
if (first.length > 2) {
return true;
} else {
return false;
}
}
function validateLastName() {
//get input password value
var last = $("#lastName").val();
// check it s length
if (last.length > 2) {
return true;
} else {
return false;
}
}
const inputs = document.querySelectorAll(".input");
function addcl() {
let parent = this.parentNode.parentNode;
parent.classList.add("focus");
}
function remcl() {
let parent = this.parentNode.parentNode;
if (this.value == "") {
parent.classList.remove("focus");
}
}
inputs.forEach(input => {
input.addEventListener("focus", addcl);
input.addEventListener("blur", remcl);
});
* {
padding: 0;
margin: 0;
box-sizing: border-box;
}
body {
font-family: 'Poppins', sans-serif;
height: 100%;
padding: 0;
margin: 0;
}
.container {
width: 100vw;
height: 100vh;
display: grid;
grid-template-columns: repeat(2, 1fr);
grid-gap: 7rem;
padding: 0 2rem;
}
.login-content {
display: flex;
justify-content: flex-start;
align-items: center;
text-align: center;
}
.container {
grid-template-columns: none;
}
form {
padding: 40px;
background-color: #efefee;
width: 460px;
box-shadow: rgba(0, 0, 0, 0.1) 0 1px 5px;
border-radius: 5px;
}
#eye {
position: fixed;
margin-left: 685px;
margin-top: ;
color: #333;
display: flex;
justify-content: center;
align-items: center;
cursor: pointer;
z-index: 3;
display: none;
}
#eye2 {
position: fixed;
margin-left: 685px;
margin-top: ;
color: #333;
display: flex;
justify-content: center;
align-items: center;
cursor: pointer;
z-index: 3;
display: none;
}
.login-content h2 {
margin: 15px 0;
color: #333;
text-transform: uppercase;
font-size: 2.9rem;
margin-bottom: 105px;
}
.login-content .input-div {
position: relative;
display: grid;
grid-template-columns: 7% 93%;
margin: 45px 0;
padding: 5px 0;
border-bottom: 2px solid #d9d9d9;
}
.login-content .input-div.one {
margin-top: 0;
}
.i {
color: #333;
display: flex;
justify-content: center;
align-items: center;
}
.i i {
transition: .3s;
}
.input-div>div {
position: relative;
height: 45px;
}
.input-div>div>h5 {
/* //Az inputnak a szövege(Username,password) */
position: absolute;
left: 10px;
top: 50%;
transform: translateY(-50%);
color: #333;
font-size: 18px;
transition: .3s;
}
.input-div:before,
.input-div:after {
content: '';
position: absolute;
bottom: -2px;
width: 0%;
height: 2px;
background-color: #38d39f;
transition: .4s;
}
.input-div:before {
right: 50%;
}
.input-div:after {
left: 50%;
}
.input-div.focus:before,
.input-div.focus:after {
width: 50%;
}
.input-div.focus>div>h5 {
top: -10px;
font-size: 15px;
}
.input-div.focus>.i>i {
color: #38d39f;
}
.input-div>div>input {
position: absolute;
left: 0;
top: 0;
width: 100%;
height: 100%;
border: none;
outline: none;
background: none;
padding: 0.5rem 0.7rem;
font-size: 1.2rem;
color: #555;
font-family: 'poppins', sans-serif;
}
.input-div.pass {
margin-bottom: 4px;
}
a {
display: block;
text-align: right;
text-decoration: none;
color: #333;
font-size: 0.9rem;
transition: .3s;
}
a:hover {
color: #38d39f;
text-decoration: underline;
}
.h6 {
font-size: 16px;
display: block;
text-align: right;
text-decoration: none;
color: #333;
font-size: 0.9rem;
transition: .3s;
}
.pasw {
width: 70%;
}
.btn {
display: block;
width: 100%;
height: 50px;
border-radius: 25px;
outline: none;
border: none;
background-image: linear-gradient(to right, #32be8f, #38d39f, #32be8f);
background-size: 200%;
font-size: 1.2rem;
color: #fff;
font-family: 'Poppins', sans-serif;
text-transform: uppercase;
margin: 1rem 0;
cursor: pointer;
transition: .5s;
}
.btn:hover {
background-position: right;
}
#media screen and (max-width: 1050px) {
.container {
grid-gap: 5rem;
}
}
#media screen and (max-width: 1000px) {
form {
width: 420px;
}
.login-content h2 {
font-size: 2.4rem;
margin: 8px 0;
margin-top: 5px;
}
#eye {
margin-left: 545px;
}
#eye2 {
margin-left: 545px;
}
}
#media screen and (max-width: 900px) {
.container {
grid-template-columns: 1fr;
}
.img {
display: none;
}
.wave {
display: none;
}
.login-content {
justify-content: center;
}
}
.login-content {
justify-content: center;
}
.text-danger {
position: fixed;
text-align: left;
margin: 0;
margin-top: 58;
font-size: 14px;
color: #e50914;
}
<div class="container">
<div class="login-content">
<form method="POST">
<h2 class="title">Sign Up</h2>
<div class="input-div one" id="inputfirstname">
<div class="i">
<i class="fas fa-user" id="iconfirstname"></i>
</div>
<div class="div">
<h5>First Name</h5>
<input type="text" id="firstName" name="firstName" autocomplete="off" class="input" required>
<span id="firstMsg"></span>
</div>
</div>
<div class="input-div lastname" id="inputlastname">
<div class="i">
<i class="fas fa-user" id="iconlastname"></i>
</div>
<div class="div">
<h5>Last Name</h5>
<input type="text" id="lastName" name="lastName" autocomplete="off" class="input" required>
<span id="lastMsg"></span>
</div>
</div>
<div class="input-div email" id="inputemail">
<div class="i">
<i class="fas fa-envelope" id="iconmail"></i>
</div>
<div class="div">
<h5>Email address</h5>
<input type="email" id="email" name="email" autocomplete="off" class="input" required>
<span id="emailMsg"></span>
</div>
</div>
<div class="input-div pass2" id="inputpass">
<div class="i">
<i class="fas fa-lock" id="iconpass"></i>
<i class="fas fa-eye" id="eye" onclick="Showfunction()"></i>
<i class="fas fa-eye-slash" id="eye2" onclick="Showfunction()"></i>
</div>
<div class="div">
<h5>Password</h5>
<input type="password" name="password" autocomplete="off" class="input" maxlength="22" id="pass" oninput="hiddenscript()" required>
<span id="passMsg"></span>
</div>
</div>
Already have account? Login in!
<input type="submit" name="submitButton" class="btn" id="btSubmit" value="Sign Up">
<h6>By clicking “SIGN UP” you agree the Terms of Use and Privacy Policy.</h6>
</form>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
I recommend you guys to save it to index.html,and style.css in a folder,because for some reason on jsfiddle,the error messages for imput fields appear at wrong position,don't know exactly why.
Sorry for bad english knowledge.
You can define an error class that changes the background-color of the :before and :after elements, which you can add or remove after validating the input.
.error.input-div:before, .error.input-div:after {
background-color: #e50914;
}
Live Example:
* {
padding: 0;
margin: 0;
box-sizing: border-box;
}
body {
font-family: 'Poppins', sans-serif;
overflow: hidden;
height: 100%;
padding: 0;
margin: 0;
}
.container {
width: 100vw;
height: 100vh;
display: grid;
grid-template-columns: repeat(2, 1fr);
grid-gap: 7rem;
padding: 0 2rem;
}
.login-content {
display: flex;
justify-content: flex-start;
align-items: center;
text-align: center;
}
.container {
grid-template-columns: none;
}
form {
padding: 40px;
background-color: #efefee;
width: 460px;
box-shadow: rgba(0, 0, 0, 0.1) 0 1px 5px;
border-radius: 5px;
}
#eye {
position: fixed;
margin-left: 685px;
margin-top: ;
color: #333;
display: flex;
justify-content: center;
align-items: center;
cursor: pointer;
z-index: 3;
display: none;
}
#eye2 {
position: fixed;
margin-left: 685px;
margin-top: ;
color: #333;
display: flex;
justify-content: center;
align-items: center;
cursor: pointer;
z-index: 3;
display: none;
}
.login-content h2 {
margin: 15px 0;
color: #333;
text-transform: uppercase;
font-size: 2.9rem;
margin-bottom: 105px;
}
.login-content .input-div {
position: relative;
display: grid;
grid-template-columns: 7% 93%;
margin: 45px 0;
padding: 5px 0;
border-bottom: 2px solid #d9d9d9;
}
.login-content .input-div.one {
margin-top: 0;
}
.i {
color: #333;
display: flex;
justify-content: center;
align-items: center;
}
.i i {
transition: .3s;
}
.input-div>div {
position: relative;
height: 45px;
}
.input-div>div>h5 {
/* //Az inputnak a szövege(Username,password) */
position: absolute;
left: 10px;
top: 50%;
transform: translateY(-50%);
color: #333;
font-size: 18px;
transition: .3s;
}
.input-div:before,
.input-div:after {
content: '';
position: absolute;
bottom: -2px;
width: 0%;
height: 2px;
background-color: #38d39f;
transition: .4s;
}
.error.input-div:before,
.error.input-div:after {
background-color: #e50914;
}
.input-div:before {
right: 50%;
}
.input-div:after {
left: 50%;
}
.input-div.focus:before,
.input-div.focus:after {
width: 50%;
}
.input-div.focus>div>h5 {
top: -10px;
font-size: 15px;
}
.input-div.focus>.i>i {
color: #38d39f;
}
.input-div>div>input {
position: absolute;
left: 0;
top: 0;
width: 100%;
height: 100%;
border: none;
outline: none;
background: none;
padding: 0.5rem 0.7rem;
font-size: 1.2rem;
color: #555;
font-family: 'poppins', sans-serif;
}
.input-div.pass {
margin-bottom: 4px;
}
a {
display: block;
text-align: right;
text-decoration: none;
color: #333;
font-size: 0.9rem;
transition: .3s;
}
a:hover {
color: #38d39f;
text-decoration: underline;
}
.h6 {
font-size: 16px;
display: block;
text-align: right;
text-decoration: none;
color: #333;
font-size: 0.9rem;
transition: .3s;
}
.pasw {
width: 70%;
}
.btn {
display: block;
width: 100%;
height: 50px;
border-radius: 25px;
outline: none;
border: none;
background-image: linear-gradient(to right, #32be8f, #38d39f, #32be8f);
background-size: 200%;
font-size: 1.2rem;
color: #fff;
font-family: 'Poppins', sans-serif;
text-transform: uppercase;
margin: 1rem 0;
cursor: pointer;
transition: .5s;
}
.btn:hover {
background-position: right;
}
#media screen and (max-width: 1050px) {
.container {
grid-gap: 5rem;
}
}
#media screen and (max-width: 1000px) {
form {
width: 420px;
}
.login-content h2 {
font-size: 2.4rem;
margin: 8px 0;
margin-top: 5px;
}
#eye {
margin-left: 545px;
}
#eye2 {
margin-left: 545px;
}
}
#media screen and (max-width: 900px) {
.container {
grid-template-columns: 1fr;
}
.img {
display: none;
}
.wave {
display: none;
}
.login-content {
justify-content: center;
}
}
.login-content {
justify-content: center;
}
.text-danger {
position: fixed;
text-align: left;
margin: 0;
margin-top: 58;
font-size: 14px;
color: #e50914;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
<!DOCTYPE html>
<html>
<script>
function Showfunction() {
var eye = document.getElementById("eye");
var eye2 = document.getElementById("eye2");
var pass = document.getElementById("pass");
if (pass.type === "password") {
pass.type = "text";
eye.style.display = "none";
eye2.style.display = "block";
} else {
pass.type = "password";
eye2.style.display = "none";
eye.style.display = "block";
}
}
function hiddenscript() {
var eye = document.getElementById("eye");
eye.style.display = "block";
}
</script>
<script>
$(document).ready(function() {
// set initially button state hidden
// use keyup event on email field
$("#email").keyup(function() {
if (validateEmail()) {
// if the email is validated
// set input email border green
$('#inputemail').css('border-bottom', 'solid 2px #38d39f').removeClass('error');
$('#iconmail').css('color', '#38d39f');
$("#emailMsg").html("<p class='text-danger'></p>");
$(':input[type="submit"]').prop('disabled', false);
// and set label
} else {
// if the email is not validated
// set border red
$('#inputemail').css('border-bottom', 'solid 2px #e50914').addClass('error');
$('#iconmail').css('color', '#e50914');
$("#emailMsg").html("<p class='text-danger'>Enter valid email.</p>");
$(':input[type="submit"]').prop('disabled', true);
}
});
$("#pass").keyup(function() {
// check
if (validatePassword()) {
// set input password border green
$('#inputpass').css('border-bottom', 'solid 2px #38d39f').removeClass('error');
$('#iconpass').css('color', '#38d39f');
$("#passMsg").html("<p class='text-danger'></p>");
$(':input[type="submit"]').prop('disabled', false);
//set passMsg
} else {
$('#inputpass').css('border-bottom', 'solid 2px #e50914').addClass('error');
$('#iconpass').css('color', '#e50914');
$("#passMsg").html("<p class='text-danger'>Password must contain at least 1 digit,<br>and need to contain at least 8 character.</p>");
$(':input[type="submit"]').prop('disabled', true);
}
});
$("#firstName").keyup(function() {
// check
if (validateFirstName()) {
// set input password border green
$('#inputfirstname').css('border-bottom', 'solid 2px #38d39f').removeClass('error');
$('#iconfirstname').css('color', '#38d39f');
$("#firstMsg").html("<p class='text-danger'></p>");
$(':input[type="submit"]').prop('disabled', false);
//set passMsg
} else {
$('#inputfirstname').css('border-bottom', 'solid 2px #e50914').addClass('error');
$('#iconfirstname').css('color', '#e50914');
$("#firstMsg").html("<p class='text-danger'>The first name must be at least 3 character long.</p>");
$(':input[type="submit"]').prop('disabled', true);
}
});
$("#lastName").keyup(function() {
// check
if (validateLastName()) {
// set input password border green
$('#inputlastname').css('border-bottom', 'solid 2px #38d39f').removeClass('error');
$('#iconlastname').css('color', '#38d39f');
$("#lastMsg").html("<p class='text-danger'></p>");
$(':input[type="submit"]').prop('disabled', false);
//set passMsg
} else {
$('#inputlastname').css('border-bottom', 'solid 2px #e50914').addClass('error');
$('#iconlastname').css('color', '#e50914');
$("#lastMsg").html("<p class='text-danger'>The last name must be at least 3 character long.</p>");
$(':input[type="submit"]').prop('disabled', true);
}
});
});
function validateEmail() {
// get value of input email
var email = $("#email").val();
// use reular expression
var reg = /^\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*$/
if (reg.test(email)) {
return true;
} else {
return false;
}
}
function validatePassword() {
var pass = $("#pass").val();
var reg = /^(?=.*\d)(?=.*[a-z])[0-9a-zA-Z]{8,}$/
if (reg.test(pass)) {
return true;
} else {
return false;
}
}
function validateFirstName() {
//get input password value
var first = $("#firstName").val();
// check it s length
if (first.length > 2) {
return true;
} else {
return false;
}
}
function validateLastName() {
//get input password value
var last = $("#lastName").val();
// check it s length
if (last.length > 2) {
return true;
} else {
return false;
}
}
</script>
<head>
<title>Animated Login Form</title>
<link rel="stylesheet" type="text/css" href="style.css">
<link href="https://fonts.googleapis.com/css?family=Poppins:600&display=swap" rel="stylesheet">
<script src="https://kit.fontawesome.com/a81368914c.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<div class="container">
<div class="login-content">
<form method="POST">
<h2 class="title">Sign Up</h2>
<div class="input-div one" id="inputfirstname">
<div class="i">
<i class="fas fa-user" id="iconfirstname"></i>
</div>
<div class="div">
<h5>First Name</h5>
<input type="text" id="firstName" name="firstName" autocomplete="off" class="input" required>
<span id="firstMsg"></span>
</div>
</div>
<div class="input-div lastname" id="inputlastname">
<div class="i">
<i class="fas fa-user" id="iconlastname"></i>
</div>
<div class="div">
<h5>Last Name</h5>
<input type="text" id="lastName" name="lastName" autocomplete="off" class="input" required>
<span id="lastMsg"></span>
</div>
</div>
<div class="input-div email" id="inputemail">
<div class="i">
<i class="fas fa-envelope" id="iconmail"></i>
</div>
<div class="div">
<h5>Email address</h5>
<input type="email" id="email" name="email" autocomplete="off" class="input" required>
<span id="emailMsg"></span>
</div>
</div>
<div class="input-div pass2" id="inputpass">
<div class="i">
<i class="fas fa-lock" id="iconpass"></i>
<i class="fas fa-eye" id="eye" onclick="Showfunction()"></i>
<i class="fas fa-eye-slash" id="eye2" onclick="Showfunction()"></i>
</div>
<div class="div">
<h5>Password</h5>
<input type="password" name="password" autocomplete="off" class="input" maxlength="22" id="pass" oninput="hiddenscript()" required>
<span id="passMsg"></span>
</div>
</div>
Already have account? Login in!
<input type="submit" name="submitButton" class="btn" id="btSubmit" value="Sign Up">
<h6>By clicking “SIGN UP” you agree the Terms of Use and Privacy Policy.</h6>
</form>
</div>
</div>
<script type="text/javascript">
const inputs = document.querySelectorAll(".input");
function addcl() {
let parent = this.parentNode.parentNode;
parent.classList.add("focus");
}
function remcl() {
let parent = this.parentNode.parentNode;
if (this.value == "") {
parent.classList.remove("focus");
}
}
inputs.forEach(input => {
input.addEventListener("focus", addcl);
input.addEventListener("blur", remcl);
});
</script>
</body>
</html>

Delete button not working after adding another entry to my Library object

I have a problem that my delete button (the yellow one) works perfectly on preloaded book library items, but it isn't on the new entry when I add a book and want to delete it... I also want you to ask what it would be the easiest way to delete books also from myLibrary array... Thanks.
I've attached my code here. Any help will be appreciated. Thanks in advance.
//DOM
const bookForm = document.querySelector(".book-form");
// Calling a form when clicking on add book button
function openNav() {
document.getElementById("myNav").style.height = "100%";
console.log("dsafsa");
}
function closeNav() {
document.getElementById("myNav").style.height = "0%";
}
// where the books will be saved...
let myLibrary = [{
title: "Harry Potter - and the Philosopher's Stone",
author: "J. K. Rowling",
pages: 223,
readStatus: "no",
},
{
title: "The Hobbit",
author: "J.R.R. Tolkien",
pages: 304,
readStatus: "yes",
},
];
// book object
function Book(title, author, pages, readStatus) {
(this.title = title),
(this.author = author),
(this.pages = pages),
(this.readStatus = readStatus);
}
let i = "";
// render the book on page load...
function render() {
const books = myLibrary;
books.forEach((book) => {
addNewBookUI(book);
});
}
render();
document.querySelector(".book-form").addEventListener("submit", (e) => {
// prevent actual submit
e.preventDefault();
// get values
const title = document.querySelector("#title").value;
const author = document.querySelector("#author").value;
const pages = document.querySelector("#pages").value;
const readStatus = document.querySelector('input[name="yes_no"]:checked')
.value;
// prevent empty fields ...
if (title === "" || author === "" || pages === "0") {
alert("Missing data");
} else {
const book = new Book(title, author, pages, readStatus);
myLibrary.push(book);
addNewBookUI(book);
clearFormFields()
}
});
function addNewBookUI(book) {
if (book.readStatus === "yes") {
i = "checked";
} else {
i = "";
}
const main = document.querySelector(".main");
const bookCard = document.createElement("div");
bookCard.classList.add("book-card");
bookCard.innerHTML = `<div class="delete_button"><button class="delete btn"><i class="fa fa-trash">
</i></button></div><div class="title">${book.title}</div><div class="author">${book.author}
</div><div class="pages">${book.pages}</div><div class="read_status">Read: <input type="checkbox" id="yes" name="readstatus" value="yes" ${i}>
</div>`;
main.appendChild(bookCard);
}
// clear form fields after submit
function clearFormFields() {
const myForm = document.getElementById("myForm");
myForm.reset();
}
// Add event listener to all deleteButton
const deleteButton = document.querySelectorAll(".delete");
// deletes book UI;
deleteButton.forEach((el) => {
el.addEventListener("click", function () {
el.parentElement.parentElement.remove()
console.log("sas")
})
})
*,
*::before,
*::after {
box-sizing: border-box;
}
body {
font-family: 'Roboto', sans-serif;
margin: 0;
padding: 0;
}
header {
color: #ffffff;
display: flex;
font-size: 1.4rem;
justify-content: space-between;
align-items: center;
background-color: #155999;
border-bottom: #172f4f solid 10px;
}
.logo {
margin-left: 10px;
}
header button {
background-color: #183153;
border: none;
text-align: left;
font-size: 0.9rem;
border-radius: 5px;
color: #ffffff;
padding: 10px 50px;
margin-right: 10px;
cursor: pointer;
}
.plus-sign {
padding-right: 7px;
}
.main {
position: absolute;
width: 100%;
height: 100%;
background-color: #183153;
display: flex;
flex-wrap: wrap;
justify-content: flex-start;
}
.book-card {
text-align: center;
font-weight: 1000;
display: flex;
flex-direction: column;
justify-content: space-evenly;
width: 250px;
height: 350px;
border-radius: 10px;
background-color: #155999;
margin-left: 20px;
margin-top: 10px;
color: #ffffff;
border: #172f4f solid 8px;
line-height: 30px;
position: relative;
padding-left: 7px;
padding-right: 7px;
box-shadow: 10px 4px 22px -5px rgba(21, 89, 153, 1);
}
.overlay {
height: 0%;
width: 100%;
position: fixed;
z-index: 1;
top: 0;
left: 0;
background-color: rgb(21, 89, 153);
background-color: rgba(21, 89, 153, 0.7);
overflow-y: hidden;
transition: 0.5s;
}
.overlay-content {
position: relative;
top: 25%;
width: 100%;
text-align: center;
margin-top: 30px;
display: flex;
flex-direction: column;
font-size: 30px;
}
.overlay a {
padding: 8px;
text-decoration: none;
font-size: 36px;
color: #ffffff;
display: block;
transition: 0.3s;
}
.overlay a:hover,
.overlay a:focus {
color: #c3c6d1;
}
.overlay .closebtn {
position: absolute;
top: 20px;
right: 45px;
font-size: 60px;
}
#media screen and (max-height: 450px) {
.overlay {
overflow-y: auto;
}
.overlay a {
font-size: 20px
}
.overlay .closebtn {
font-size: 40px;
top: 15px;
right: 35px;
}
}
.book-card div {
margin-top: 15px;
}
/* Style buttons */
.btn {
background-color: #ffd43b;
/* Blue background */
border: none;
/* Remove borders */
color: red;
/* White text */
padding: 12px 16px;
/* Some padding */
font-size: 16px;
/* Set a font size */
cursor: pointer;
/* Mouse pointer on hover */
border-radius: 50%;
position: absolute;
top: -20px;
right: -15px;
}
/* Darker background on mouse-over */
.btn:hover {
background-color: #183153;
}
.delete_button {
top: 0;
right: 0;
}
form div {
margin-top: 15px;
font-family: 'Roboto', sans-serif;
color: white;
font-weight: bold;
font-size: 30px;
margin-bottom: 10px;
}
.radiobutton {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
.form-flex {
display: flex;
justify-content: center;
flex-direction: column;
align-items: center;
}
.form-flex input {
width: 50%;
border-radius: 5px;
height: 30px;
margin-top: 5px
}
.form-flex input::placeholder {
text-align: center;
}
input[type=submit] {
background-color: #183153;
border: none;
text-align: left;
font-size: 0.9rem;
border-radius: 5px;
color: #ffffff;
padding: 10px 50px;
margin-top: -30px;
cursor: pointer;
}
.radiobutton p {
margin-top: 10px;
margin-bottom: 30px;
}
.flexbuttons {
display: flex;
margin-top: -50px;
margin-bottom: -25px;
}
input[type="text"] {
font-size: 24px;
text-align: center;
}
<!-- The overlay -->
<div id="myNav" class="overlay">
<!-- Button to close the overlay navigation -->
×
<!-- Overlay content -->
<div class="overlay-content">
<form id="myForm" class="book-form">
<div class="form-flex">
<label for="title">Book name:</label>
<input type="text" id="title" name="title" placeholder="Book name...">
</div>
<div class="form-flex">
<label for="author">Book author:</label>
<input type="text" id="author" name="author" placeholder="Book author...">
</div >
<div class="form-flex">
<label for="pages">Pages:</label>
<input type="number" id="pages" placeholder="0" name="pages">
</div>
<div class="radiobutton">
<p>Have you read a book?</p>
<div class="flexbuttons">
<div>
<p><input type="radio" id="huey" name="yes_no" value="yes" checked>
<label for="huey">yes</label>
</p>
</div>
<div>
<p><input type="radio" id="no" name="yes_no" value="no">
<label for="dewey">no</label>
</p>
</div>
</div>
</div>
<div><input type="submit" value="Add Book"></div>
</form>
</div>
</form>
</div>
</div>
</div>
<header>
<div class="logo">
<h1><i class="fa fa-book" aria-hidden="true"></i>
</i>Library
</h1>
</div>
<div class="button">
<button onclick="openNav()" class="add-book">
<i class="fa fa-plus plus-sign"></i>
Add book</button>
</div>
</header>
<div class="main">
</div>
<script src="./index.js" defer></script>
<script src="https://use.fontawesome.com/30a34909cc.js"></script>
You assigned the click event at loading time to all existing buttons with class=="delete". This will naturally not include the ones you might add dynamically at a later stage.
If you want all ".delete" buttons to have the click-event attached to them you need to do a "delegated event attachment" (edited, removes myLibrary element too now):
// Add event listener to all current and future deleteButtons
document.querySelector('.main').onclick=ev=>{
let el= ev.target.classList.contains('fa-trash')? ev.target.parentElement : ev.target.classList.contains('delete') ? ev.target : false;
if (el) {
let card=el.parentElement.parentElement; // book-card DOM element
// remove myLibrary array-element here:
myLibrary.splice( [...card.parentElement.children].indexOf(card) ,1);
console.log(myLibrary)
// remove card DOM element:
card.remove()
}
}
This will bind the click event handler to the .main div and will react only if the clicked element has a class=='fa-trash' or class=='delete'. In the first case it will "move up" one level (assign the parent element, i. e. the button to el), otherwise the clicked element is the button itself. If none of these classes are found, el becomes false and nothing happens. Otherwise the "Grandparent" of el is removed with `el.parentElement.parentElement.remove()' .
And please try and make your MCVE a little smaller next time, as it no fun to handle this amount of code in a small Stackoverflow snippet window! A true MCVE will get you more and faster responses!
Below is a working snippet, check it out:
//DOM
const bookForm = document.querySelector(".book-form");
// Calling a form when clicking on add book button
function openNav() {
document.getElementById("myNav").style.height = "100%";
console.log("dsafsa");
}
function closeNav() {
document.getElementById("myNav").style.height = "0%";
}
// where the books will be saved...
let myLibrary = [
{
title: "Harry Potter - and the Philosopher's Stone",
author: "J. K. Rowling",
pages: 223,
readStatus: "no",
},
{
title: "The Hobbit",
author: "J.R.R. Tolkien",
pages: 304,
readStatus: "yes",
},
];
// book object
function Book(title, author, pages, readStatus) {
(this.title = title),
(this.author = author),
(this.pages = pages),
(this.readStatus = readStatus);
}
let i = "";
// render the book on page load...
function render() {
const books = myLibrary;
books.forEach((book) => {
addNewBookUI(book);
});
}
render();
document.querySelector(".book-form").addEventListener("submit", (e) => {
// prevent actual submit
e.preventDefault();
// get values
const title = document.querySelector("#title").value;
const author = document.querySelector("#author").value;
const pages = document.querySelector("#pages").value;
const readStatus = document.querySelector('input[name="yes_no"]:checked')
.value;
// prevent empty fields ...
if (title === "" || author === "" || pages === "0") {
alert("Missing data");
} else {
const book = new Book(title, author, pages, readStatus);
myLibrary.push(book);
addNewBookUI(book);
clearFormFields()
}
});
function addNewBookUI(book) {
if (book.readStatus === "yes") {
i = "checked";
} else {
i = "";
}
const main = document.querySelector(".main");
const bookCard = document.createElement("div");
bookCard.classList.add("book-card");
bookCard.innerHTML = `<div class="delete_button"><button class="delete btn"><i class="fa fa-trash">
</i></button></div><div class="title">${book.title}</div><div class="author">${book.author}
</div><div class="pages">${book.pages}</div><div class="read_status">Read: <input type="checkbox" id="yes" name="readstatus" value="yes" ${i}>
</div>`;
main.appendChild(bookCard);
}
// clear form fields after submit
function clearFormFields() {
const myForm = document.getElementById("myForm");
myForm.reset();
}
// Add event listener to all deleteButton
document.querySelector('.main').onclick=ev=>{
let el= ev.target.classList.contains('fa-trash')? ev.target.parentElement : ev.target.classList.contains('delete') ? ev.target : false;
if (el) {
let card=el.parentElement.parentElement;
myLibrary.splice( [...card.parentElement.children].indexOf(card) ,1);
console.log(myLibrary)
card.remove()
}
}
*, *::before, *::after {
box-sizing: border-box;
}
body {
font-family: 'Roboto', sans-serif;
margin: 0;
padding: 0;
}
header {
color: #ffffff;
display: flex;
font-size: 1.4rem;
justify-content: space-between;
align-items: center;
background-color:#155999;
border-bottom: #172f4f solid 10px;
}
.logo {
margin-left: 10px;
}
header button {
background-color: #183153;
border: none;
text-align: left;
font-size: 0.9rem;
border-radius: 5px;
color: #ffffff;
padding: 10px 50px;
margin-right: 10px;
cursor: pointer;
}
.plus-sign {
padding-right: 7px;
}
.main {
position: absolute;
width: 100%;
height: 100%;
background-color: #183153;
display: flex;
flex-wrap: wrap;
justify-content: flex-start;
}
.book-card {
text-align: center;
font-weight: 1000;
display: flex;
flex-direction: column;
justify-content: space-evenly;
width: 250px;
height: 350px;
border-radius: 10px;
background-color: #155999;
margin-left: 20px;
margin-top:10px;
color: #ffffff;
border: #172f4f solid 8px;
line-height: 30px;
position: relative;
padding-left: 7px;
padding-right: 7px;
box-shadow: 10px 4px 22px -5px rgba(21,89,153,1);
}
.overlay {
height: 0%;
width: 100%;
position: fixed;
z-index: 1;
top: 0;
left: 0;
background-color: rgb(21,89,153);
background-color: rgba(21,89,153,0.7);
overflow-y: hidden;
transition: 0.5s;
}
.overlay-content {
position: relative;
top: 25%;
width: 100%;
text-align: center;
margin-top: 30px;
display: flex;
flex-direction: column;
font-size: 30px;
}
.overlay a {
padding: 8px;
text-decoration: none;
font-size: 36px;
color: #ffffff;
display: block;
transition: 0.3s;
}
.overlay a:hover, .overlay a:focus {
color: #c3c6d1;
}
.overlay .closebtn {
position: absolute;
top: 20px;
right: 45px;
font-size: 60px;
}
#media screen and (max-height: 450px) {
.overlay {overflow-y: auto;}
.overlay a {font-size: 20px}
.overlay .closebtn {
font-size: 40px;
top: 15px;
right: 35px;
}
}
.book-card div {
margin-top:15px;
}
/* Style buttons */
.btn {
background-color: #ffd43b; /* Blue background */
border: none; /* Remove borders */
color: red; /* White text */
padding: 12px 16px; /* Some padding */
font-size: 16px; /* Set a font size */
cursor: pointer; /* Mouse pointer on hover */
border-radius: 50%;
position:absolute;
top:-20px;
right:-15px;
}
/* Darker background on mouse-over */
.btn:hover {
background-color: #183153;
}
.delete_button {
top:0;
right:0;
}
form div {
margin-top: 15px;
font-family: 'Roboto', sans-serif;
color:white;
font-weight: bold;
font-size: 30px;
margin-bottom: 10px;
}
.radiobutton {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
.form-flex {
display: flex;
justify-content: center;
flex-direction: column;
align-items: center;
}
.form-flex input {
width: 50%;
border-radius: 5px;
height: 30px;
margin-top: 5px
}
.form-flex input::placeholder {
text-align: center;
}
input[type=submit] {
background-color: #183153;
border: none;
text-align: left;
font-size: 0.9rem;
border-radius: 5px;
color: #ffffff;
padding: 10px 50px;
margin-top: -30px;
cursor: pointer;
}
.radiobutton p {
margin-top:10px;
margin-bottom: 30px;
}
.flexbuttons {
display: flex;
margin-top: -50px;
margin-bottom: -25px;
}
input[type="text"]
{
font-size:24px;
text-align: center;
}
JS:
//DOM
const bookForm = document.querySelector(".book-form");
<!-- The overlay -->
<div id="myNav" class="overlay">
<!-- Button to close the overlay navigation -->
×
<!-- Overlay content -->
<div class="overlay-content">
<form id="myForm" class="book-form">
<div class="form-flex">
<label for="title">Book name:</label>
<input type="text" id="title" name="title" placeholder="Book name...">
</div>
<div class="form-flex">
<label for="author">Book author:</label>
<input type="text" id="author" name="author" placeholder="Book author...">
</div >
<div class="form-flex">
<label for="pages">Pages:</label>
<input type="number" id="pages" placeholder="0" name="pages">
</div>
<div class="radiobutton">
<p>Have you read a book?</p>
<div class="flexbuttons">
<div><p><input type="radio" id="huey" name="yes_no" value="yes" checked>
<label for="huey">yes</label></p>
</div>
<div><p><input type="radio" id="no" name="yes_no" value="no">
<label for="dewey">no</label></p>
</div>
</div>
</div>
<div><input type="submit" value="Add Book"></div>
</form>
</div>
</form>
</div>
</div>
</div>
<header>
<div class="logo">
<h1><i class="fa fa-book" aria-hidden="true"></i>
</i>Library</h1>
</div>
<div class="button">
<button onclick="openNav()" class="add-book">
<i class="fa fa-plus plus-sign"></i>
Add book</button>
</div>
</header>
<div class="main">
</div>
<script src="./index.js" defer></script>
<script src="https://use.fontawesome.com/30a34909cc.js"></script>

Not refreshing second select dropdown list

I am new in web development, I appreciate your help with this problem. I am trying to build and HTML form using Apps Script, materialize CSS and JavaScript. I have two dependent selects, the first one with id "tipo" and the second with id "nov". These two are dependent, if i choose in the first select an option, only for the second select must appears only the options that belongs to that category. for example, when i select in the first dropdown the option calls "servicios publicos" the second select only must show the options: agua, luz, energia, gas and telef/internet. The problem is in the second select with id "nov" its not refreshing, only appears the option calls "agua", but the select its not working, when you clicked it.
document.addEventListener('DOMContentLoaded', function () {
var elems = document.querySelectorAll('select');
var instances = M.FormSelect.init(elems);
google.script.run.withSuccessHandler(populateWords).getWords();
document.getElementById("frmRegister").addEventListener("submit", empres);
document.getElementById('nov').addEventListener("click", 'select');
});
function populateWords(words) {
var autocomplete = document.getElementById('pto');
var instances2 = M.Autocomplete.init(autocomplete, {
data: words
});
}
function empres(e) {
// prevenir un evento por defecto
e.preventDefault();
var userInfo = {};
userInfo.punto = document.getElementById("pto").value;
userInfo.tiponov = document.getElementById("tipo").value;
userInfo.novedad = document.getElementById("nov").value;
userInfo.check = document.getElementById("ch").value;
userInfo.detalle = document.getElementById("textarea1").value;
google.script.run.registroEmp(userInfo);
document.getElementById("pto").value = "";
document.getElementById("tipo").value = "";
document.getElementById("nov").value = "";
document.getElementById("ch").value = "";
document.getElementById("textarea1").value = "";
var selectList = document.getElementById("tipo");
selectList.selectedIndex = 0;
M.FormSelect.init(selectList);
var selectList2 = document.getElementById("nov");
selectList2.selectedIndex = 0;
M.FormSelect.init(selectList2);
var selectList3 = document.getElementById("ch");
selectList3.selectedIndex = 0;
M.FormSelect.init(selectList3);
//var datePicker =document.getElementById("fecha");
//datePicker.value ="";
//M.Datepicker.init(datePicker);
}
* {
top: 0;
left: 0;
margin: 0;
padding: 0;
}
.form-row {
margin-bottom: 0px;
}
.row1 {
display: inline-block;
margin-right: auto;
margin-left: auto;
padding: 2px;
}
.warning-bar {
visibility: hidden;
}
img {
width: 250px;
height: auto;
margin: 10px;
margin-top: 8px;
padding-top: 15px;
}
.page-footer {
background: black;
border-top: 1px solid #e4e4e4;
}
.container-footer {
color: black;
background-color: #FFFFFF;
margin-left:
}
.page-footer.footer-copyright {
background-color: #FFFFFF;
}
.div.footer-copyright {
color: black;
background-color: #FFFFFF;
}
.footer.page-footer {
background-color: black;
}
.page-footer .footer-copyright {
background-color: #FFFFFF;
border-top: 1px solid #e4e4e4;
}
p.black-text-copyright {
padding-left: 15px;
text-align: left;
}
.tooltip {
position: relative;
display: inline-block;
border-bottom: 1px dotted #FFFFFF;
}
.tooltip .tooltiptext {
visibility: hidden;
width: 120px;
background-color: #17202A;
color: #fff;
text-align: center;
border-radius: 6px;
padding: 5px 0;
position: absolute;
z-index: 1;
bottom: 125%;
left: 50%;
margin-left: -60px;
opacity: 0;
transition: opacity 0.3s;
}
.tooltip .tooltiptext::after {
content: "";
position: absolute;
top: 100%;
left: 50%;
margin-left: -5px;
border-width: 5px;
border-style: solid;
border-color: #555 transparent transparent transparent;
}
.tooltip:hover .tooltiptext {
visibility: visible;
opacity: 1;
}
h3 {
text-align: center;
}
btn {
float: none;
text-align: center;
margin-bottom: 20px;
padding-left: 30px;
padding-top: 10px;
}
h5 {
text-align: center;
}
.title {
color: red;
text-align: center;
}
h4 {
text-align: center;
}
}
body {
background-image: url("https://images.pexels.com/photos/3717291/pexels-photo-3717291.jpeg");
width: 100%;
margin: 0;
padding: 0;
font-family: 'Josefin Sans', sans-serif;
}
button {
margin-bottom: 20px;
}
html {
top: 0;
left: 0;
margin: 0;
padding: 0;
width: 100%;
}
.login {
width: 400px;
margin: 16px auto;
font-size: 16px;
position: relative;
}
}
.frmHome {
margin-left: auto;
margin-right: auto;
}
.select-wrapper .caret {
position: absolute;
right: 0;
top: 0;
bottom: 0;
margin: auto 0;
z-index: 0;
fill: rgba(0, 0, 0, 0.0);
}
.login-triangle {
width: 0;
margin-right: auto;
margin-left: auto;
border: 12px solid transparent;
border-bottom-color: #1ABC9C;
margin-top: 60px;
}
.login-header {
background: #1ABC9C;
padding: 20px;
font-size: 1.4em;
font-weight: normal;
text-align: center;
border-radius: 4px;
color: #fff;
margin-bottom: 0;
margin-top: 0px;
}
.login-container {
background: #FDFEFE;
padding: 30px;
margin-left: auto;
margin-right: auto;
border: 1px solid #D5D8DC;
border-radius: 6px;
margin-top: 0px;
}
.textarea.materialize-textarea {
margin-left: auto;
margin-right: auto;
}
<!DOCTYPE html>
<html>
<head>
<base target="_Self">
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
<link href="https://fonts.googleapis.com/css2?family=Josefin+Sans&display=swap" rel="stylesheet">
<?!= include("page-css"); ?>
</head>
<body>
<img style="position:absolute; width:100%; height:auto; margin:0; padding:0; background:https://images.pexels.com/photos/3717291/pexels-photo-3717291.jpeg"
src="https://images.pexels.com/photos/3717291/pexels-photo-3717291.jpeg">
<div class="login">
<div class="login-triangle"></div>
<h2 class="login-header">Registro Novedades</h2>
<form id="frmRegister" class="login-container">
<div class="row">
<div class="input-field col s12">
<i style="color:#1ABC9C" class="material-icons prefix">search</i>
<input type="text" id="pto" class="autocomplete">
<label for="pto">Consulta el punto de servicio</label>
</div>
</div>
<div class="row">
<div class="input-field col s12">
<select id="tipo" onchange="ChangeCarList()">
<option value=""></option>
<option value="SP">Servicios Públicos</option>
<option value="SG">Seguridad</option>
<option value="AD">Administración</option>
<option value="CV">Convivencia</option>
</select>
<label for="tipo">Selecciona el tipo de novedad</label>
</div>
<div class="input-field col s12">
<select id="nov"></select>
<label>Novedad</label>
</div>
</div>
<script>
var carsAndModels = {};
carsAndModels['SP'] = ['Agua', 'Aseo', 'Energia', 'Gas', 'Telef/Internet'];
carsAndModels['SG'] = ['Hurto a residencias', 'Intervención Policia Nal', 'Orden Público',
'Lesiones Personales', 'Alarma', 'Daños Infraestruc/Bienes'
];
carsAndModels['AD'] = ['M6', 'X5', 'Z3'];
function ChangeCarList() {
var carList = document.getElementById("tipo");
var modelList = document.getElementById("nov");
var selCar = carList.options[carList.selectedIndex].value;
while (modelList.options.length) {
modelList.remove(0);
}
var cars = carsAndModels[selCar];
if (cars) {
var i;
for (i = 0; i < cars.length; i++) {
var car = new Option(cars[i], i);
modelList.options.add(car);
}
}
}
</script>
<div class="row">
<div class="input-field col s12">
<select id="ch">
<option value="" disabled selected>Generar Alerta</option>
<option>Si</option>
<option>No</option>
</select>
<label>¿Desea generar alerta de pánico?</label>
</div>
</div>
<div class="input-field col s12">
<textarea id="textarea1" class="materialize-textarea"></textarea>
<label for="textarea1">Ingrese el detalle del evento</label>
</div>
<button style="width:100%; margin-top:20px;" class="waves-effect waves-light btn-small" type="submit"
name="action">Enviar
<i class="material-icons right">send</i>
</button>
</form>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
<script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
<?!= include("page-js"); ?>
</body>
</html>
The problem is: the select input is rendered with Materialize on page load, it adds HTML elements to you're initial code to make the UI looks the way it looks,
All you have to do is to trigger this after you add the select options, so I moved this code from Javascript file ( which triggers only once at the beginning ) into the ChangeCarList() so that the Materialize can create the proper dropdown with new options.
var selectList2 = document.getElementById("nov");
selectList2.selectedIndex = 0;
M.FormSelect.init(selectList2);
Since you already have the variable modelList contains the nov, I just used it instead of re-selecting it.
I hope this is the result you were looking for, Good Luck.
document.addEventListener('DOMContentLoaded', function () {
var elems = document.querySelectorAll('select');
var instances = M.FormSelect.init(elems);
//google.script.run.withSuccessHandler(populateWords).getWords();
document.getElementById("frmRegister").addEventListener("submit", empres);
// document.getElementById('nov').addEventListener("click", 'select');
});
function populateWords(words) {
var autocomplete = document.getElementById('pto');
var instances2 = M.Autocomplete.init(autocomplete, {
data: words
});
}
function empres(e) {
e.preventDefault();
var userInfo = {};
userInfo.punto = document.getElementById("pto").value;
userInfo.tiponov = document.getElementById("tipo").value;
userInfo.novedad = document.getElementById("nov").value;
userInfo.check = document.getElementById("ch").value;
userInfo.detalle = document.getElementById("textarea1").value;
google.script.run.registroEmp(userInfo);
document.getElementById("pto").value = "";
document.getElementById("tipo").value = "";
document.getElementById("nov").value = "";
document.getElementById("ch").value = "";
document.getElementById("textarea1").value = "";
var selectList = document.getElementById("tipo");
selectList.selectedIndex = 0;
M.FormSelect.init(selectList);
var selectList3 = document.getElementById("ch");
selectList3.selectedIndex = 0;
M.FormSelect.init(selectList3);
//var datePicker =document.getElementById("fecha");
//datePicker.value ="";
//M.Datepicker.init(datePicker);
}
* {
top: 0;
left: 0;
margin: 0;
padding: 0;
}
.form-row {
margin-bottom: 0px;
}
.row1 {
display: inline-block;
margin-right: auto;
margin-left: auto;
padding: 2px;
}
.warning-bar {
visibility: hidden;
}
img {
width: 250px;
height: auto;
margin: 10px;
margin-top: 8px;
padding-top: 15px;
}
.page-footer {
background: black;
border-top: 1px solid #e4e4e4;
}
.container-footer {
color: black;
background-color: #FFFFFF;
margin-left:
}
.page-footer.footer-copyright {
background-color: #FFFFFF;
}
.div.footer-copyright {
color: black;
background-color: #FFFFFF;
}
.footer.page-footer {
background-color: black;
}
.page-footer .footer-copyright {
background-color: #FFFFFF;
border-top: 1px solid #e4e4e4;
}
p.black-text-copyright {
padding-left: 15px;
text-align: left;
}
.tooltip {
position: relative;
display: inline-block;
border-bottom: 1px dotted #FFFFFF;
}
.tooltip .tooltiptext {
visibility: hidden;
width: 120px;
background-color: #17202A;
color: #fff;
text-align: center;
border-radius: 6px;
padding: 5px 0;
position: absolute;
z-index: 1;
bottom: 125%;
left: 50%;
margin-left: -60px;
opacity: 0;
transition: opacity 0.3s;
}
.tooltip .tooltiptext::after {
content: "";
position: absolute;
top: 100%;
left: 50%;
margin-left: -5px;
border-width: 5px;
border-style: solid;
border-color: #555 transparent transparent transparent;
}
.tooltip:hover .tooltiptext {
visibility: visible;
opacity: 1;
}
h3 {
text-align: center;
}
btn {
float: none;
text-align: center;
margin-bottom: 20px;
padding-left: 30px;
padding-top: 10px;
}
h5 {
text-align: center;
}
.title {
color: red;
text-align: center;
}
h4 {
text-align: center;
}
}
body {
background-image: url("https://images.pexels.com/photos/3717291/pexels-photo-3717291.jpeg");
width: 100%;
margin: 0;
padding: 0;
font-family: 'Josefin Sans', sans-serif;
}
button {
margin-bottom: 20px;
}
html {
top: 0;
left: 0;
margin: 0;
padding: 0;
width: 100%;
}
.login {
width: 400px;
margin: 16px auto;
font-size: 16px;
position: relative;
}
}
.frmHome {
margin-left: auto;
margin-right: auto;
}
.select-wrapper .caret {
position: absolute;
right: 0;
top: 0;
bottom: 0;
margin: auto 0;
z-index: 0;
fill: rgba(0, 0, 0, 0.0);
}
.login-triangle {
width: 0;
margin-right: auto;
margin-left: auto;
border: 12px solid transparent;
border-bottom-color: #1ABC9C;
margin-top: 60px;
}
.login-header {
background: #1ABC9C;
padding: 20px;
font-size: 1.4em;
font-weight: normal;
text-align: center;
border-radius: 4px;
color: #fff;
margin-bottom: 0;
margin-top: 0px;
}
.login-container {
background: #FDFEFE;
padding: 30px;
margin-left: auto;
margin-right: auto;
border: 1px solid #D5D8DC;
border-radius: 6px;
margin-top: 0px;
}
.textarea.materialize-textarea {
margin-left: auto;
margin-right: auto;
}
.input-field input {
padding-left: 10px
}
.select-wrapper input.select-dropdown {
text-indent: 25px
}
<!DOCTYPE html>
<html>
<head>
<base target="_Self">
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
<link href="https://fonts.googleapis.com/css2?family=Josefin+Sans&display=swap" rel="stylesheet">
<link rel="stylesheet" href="style.css">
</head>
<body>
<img style="position:absolute; width:100%; height:auto; margin:0; padding:0; background:https://images.pexels.com/photos/3717291/pexels-photo-3717291.jpeg"
src="https://images.pexels.com/photos/3717291/pexels-photo-3717291.jpeg">
<div class="login">
<div class="login-triangle"></div>
<h2 class="login-header">Registro Novedades</h2>
<form id="frmRegister" class="login-container">
<div class="row">
<div class="input-field col s12">
<i style="color:#1ABC9C" class="material-icons prefix">search</i>
<input type="text" id="pto" class="autocomplete">
<label for="pto">Consulta el punto de servicio</label>
</div>
</div>
<div class="row">
<div class="input-field col s12">
<select id="tipo" onchange="ChangeCarList()">
<option value=""></option>
<option value="SP">Servicios Públicos</option>
<option value="SG">Seguridad</option>
<option value="AD">Administración</option>
<option value="CV">Convivencia</option>
</select>
<label for="tipo">Selecciona el tipo de novedad</label>
</div>
<div class="input-field col s12 nov-select">
<select id="nov">
</select>
<label>Novedad</label>
</div>
</div>
<script>
var carsAndModels = {};
carsAndModels['SP'] = ['Agua', 'Aseo', 'Energia', 'Gas', 'Telef/Internet'];
carsAndModels['SG'] = ['Hurto a residencias', 'Intervención Policia Nal', 'Orden Público',
'Lesiones Personales', 'Alarma', 'Daños Infraestruc/Bienes'
];
carsAndModels['AD'] = ['M6', 'X5', 'Z3'];
function ChangeCarList() {
var carList = document.getElementById("tipo");
var modelList = document.getElementById("nov");
var selCar = carList.options[carList.selectedIndex].value;
while (modelList.options.length) {
modelList.remove(0);
}
var cars = carsAndModels[selCar];
if (cars) {
for (var i = 0; i < cars.length; i++) {
var car = new Option(cars[i], i);
modelList.options.add(car)
}
}
modelList.selectedIndex = 0;
M.FormSelect.init(modelList);
}
</script>
<div class="row">
<div class="input-field col s12">
<select id="ch">
<option value="" disabled selected>Generar Alerta</option>
<option>Si</option>
<option>No</option>
</select>
<label>¿Desea generar alerta de pánico?</label>
</div>
</div>
<div class="input-field col s12">
<textarea id="textarea1" class="materialize-textarea"></textarea>
<label for="textarea1">Ingrese el detalle del evento</label>
</div>
<button style="width:100%; margin-top:20px;" class="waves-effect waves-light btn-small" type="submit"
name="action">Enviar
<i class="material-icons right">send</i>
</button>
</form>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
<script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
<script src="index.js"></script>
</body>
</html>
<div class="input-field col s12">
<div class="select-wrapper">
<select id="tipo" onchange="ChangeCarList()" tabindex="-1">
<option value=""></option>
<option value="SP">Servicios Públicos</option>
<option value="SG">Seguridad</option>
<option value="AD">Administración</option>
<option value="CV">Convivencia</option>
</select>
</div>
<label for="tipo">Selecciona el tipo de novedad</label>
</div>

Javascript - I can not sum the inputs in the cloned divs

I'm a level 0 newbie, and I'm cloning some divs (here the script works very well), to which I added some inputs with different values, and what I'm looking for is to be able to sum the values ​​(only of the cloned inputs), but the script does not he reads. Only sum ALL the html inputs.
// Script for clone the div´s
$(document).ready(function() {
$("#comp-p1").click(function() {
$("#cont-p1").clone().appendTo(".derecha");
});
// =============
$("#comp-p2").click(function() {
$("#cont-p2").clone().appendTo(".derecha");
});
// =============
$("#comp-p3").click(function() {
$("#cont-p3").clone().appendTo(".derecha");
});
});
// =============================================================
// New Script for sum inputs
const suma = function() {
var x = document.getElementsByClassName("add-prod");
let sum = 0;
for (var i = 0; i < x.length; i++) {
console.log(x[i].value)
sum += parseFloat(x[i].value);
}
console.log(sum);
return sum;
}
//console.log(suma());
document.getElementById("total").value = suma();
// =============================================================
// Old Script for sum inputs
/*$(document).ready(function() {
function sumInputs(e) {
e.preventDefault();
var valores = $('.derecha').children('input');
var suma = 0;
$.each(valores, function() {
valor = $(this).val();
suma += Number(valor);
});
valores = document.getElementById('total');
$(valores).val(suma);
}
$('#sumup').on('click', sumInputs);
});*/
body {
margin: 0 auto;
color: #323232;
width: 100%;
height: 100%;
line-height: 1.5;
font-family: 'Roboto', serif
}
#container {
width: 500px;
margin: 0 auto
}
#container p {
display: inline-block;
margin-top: 20px
}
span {
font-weight: bold;
text-decoration: underline
}
#productos {
display: none
}
.img-prod {
display: inline-block;
float: left;
background: #000;
margin-right: 10px
}
.img-prod img {
width: 100%;
height: auto;
max-width: 70px;
display: block;
border: 0
}
#comp-p1,
#comp-p2,
#comp-p3 {
width: 120px;
height: 30px;
margin-top: 15px;
background: green;
padding: 10px 0 5px;
text-align: center;
vertical-align: middle;
color: #fff;
cursor: pointer
}
.derecha {
border: solid 1px #999;
max-height: 400px;
width: 350px;
margin: 0 auto;
text-align: center;
padding: 10px 0;
overflow-y: auto;
float: right
}
#producto-1,
#producto-2,
#producto-3 {
display: inline-block;
width: 220px;
padding: 10px;
float: left;
text-align: left;
font-size: .9em;
margin-right: 5px
}
#producto-1 {
background: green;
color: #fff
}
#producto-2 {
background: #add8e6;
color: #000
}
#producto-3 {
background: #666;
color: #fff
}
.cont-p {
display: inline-block;
margin: 7px auto;
line-height: 1
}
.bbp {
display: inline-block;
float: right;
width: 24px;
height: 24px;
text-align: center;
background: red;
color: #fff;
margin-left: 5px;
line-height: 1.5;
cursor: pointer
}
.cont-num {
float: left;
width: 24px;
height: 24px;
margin: 20px 5px 0 18px;
padding: 4px 3px 3px;
background: red;
text-align: center;
font-size: 16px;
font-family: Arial, sans-serif;
color: #fff
}
#mostrar {
display: none
}
#mostrar {
width: 100px;
margin: 70px 0 0;
padding: 10px;
text-align: center;
background: grey;
color: #fff;
cursor: pointer
}
/* ==== Style of Sume ==== */
.derecha input {
width: 40px;
display: block;
margin: 0 auto 10px 0;
padding: 2px 0;
background: #f2f2f2;
border: none;
border: 1px solid #000;
text-align: center
}
#cont-resultado {
text-align: center;
width: 110px;
margin-top: 70px;
background: grey;
padding: 5px 10px 10px;
color: #fff
}
#cont-resultado input {
display: inline-block;
margin: 10px auto;
background: #fff;
color: #000;
border: 1px solid #000;
padding: 8px 0
}
#cont-resultado p {
display: inline-block;
text-decoration: none;
color: #fff;
background: grey;
padding: 8px 10px;
cursor: pointer
}
#total {
display: block;
width: 80px;
text-align: center
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="container">
<div id="productos">
<!-- =============== -->
<div id="cont-p1" class="cont-p">
<div id="producto-1">
<div class="img-prod"><img src="https://upload.wikimedia.org/wikipedia/commons/3/39/Lichtenstein_img_processing_test.png"> </div>cont-p1 cloned!<br><br>Input Value = 1</div>
<input class="add-prod" type="num" value="1">
<div class="bbp" onclick="restar();restardos();this.parentNode.parentNode.removeChild(this.parentNode);">X</div>
</div>
<!-- =============== -->
<div id="cont-p2" class="cont-p">
<div id="producto-2">
<div class="img-prod"><img src="https://upload.wikimedia.org/wikipedia/commons/3/39/Lichtenstein_img_processing_test.png"></div>
cont-p2 cloned!<br><br>Input Value = 1</div>
<input class="add-prod" type="num" value="1">
<div class="bbp" onclick="restar();restardos();this.parentNode.parentNode.removeChild(this.parentNode);">X</div>
</div>
<!-- =============== -->
<div id="cont-p3" class="cont-p">
<div id="producto-3">
<div class="img-prod"><img src="https://upload.wikimedia.org/wikipedia/commons/3/39/Lichtenstein_img_processing_test.png"></div>
cont-p3 cloned!<br><br>Input Value = 198</div>
<input class="add-prod" type="num" value="198">
<div class="bbp" onclick="restar();restardos();this.parentNode.parentNode.removeChild(this.parentNode);">X</div>
</div>
<!-- =============== -->
</div>
<!-- // productos -->
<div class="derecha"></div>
<div id="comp-p1" onClick="clickME();clickME2();">Clone 1</div>
<div id="comp-p2" onClick="clickME();clickME2();">Clone 2</div>
<div id="comp-p3" onClick="clickME();clickME2();">Clone 3</div>
<div class="cont-num" id="clicks">0</div>
<div class="cont-num" id="clicksdos">0</div>
<div id="cont-resultado">
<span>RESULT:</span><br>
<input name="total" id="total">
<br>Is the sum of the cloned divs
<!--<p id='sumup'>Ver total</p>-->
</div>
<p><span>NOTE:</span><br>Here we are looking for only the cloned inputs can be sumed (and see the result in the box color gray).<br><br>The problem is that the current script does not apply a sume of the cloned inputs only... it adds ALL the inputs presents
in the html...<br><br>So (1), how do you sum only the cloned inputs, ignoring those that are outside...?<br><br>And (2) also, how to subtract from the total result all the cloned divs that are deleted...?</p>
</div>
<!-- // container -->
<script>
// Script that adds and subtracts the clicks
var clicks = 0;
function clickME() {
clicks += 1;
document.getElementById("clicks").innerHTML = clicks
}
var clicksdos = 0;
function clickME2() {
clicksdos += 1;
document.getElementById("clicksdos").innerHTML = clicksdos;
if (clicksdos === 1) {
document.getElementById("cont-resultado").style.display = "block";
}
}
if (clicksdos === 0) {
document.getElementById("cont-resultado").style.display = "none";
}
function restar() {
if (clicks > 0) clicks -= 1;
document.getElementById("clicks").innerHTML = clicks;
}
function restardos() {
if (clicksdos > 0) clicksdos -= 1;
document.getElementById("clicksdos").innerHTML = clicksdos;
if (clicksdos === 0) {
document.getElementById("cont-resultado").style.display = "none";
}
}
</script>
Ok, you need a couple of changes.
First of you need to run a query selector and get only the elements inside the destination.
const suma = function () {
// NOTE: The query selector is very specific
let x = Array.from(document.querySelectorAll(".derecha div .add-prod"));
console.log(x);
let sum = 0;
for (var i = 0; i < x.length; i++) {
console.log(x[i].value)
sum += parseFloat(x[i].value);
}
console.log(sum);
return sum;
}
Next you will need to call you SUM method each time you add an item:
$(document).ready(function () {
$("#comp-p1").click(function () {
$("#cont-p1").clone().appendTo(".derecha");
document.getElementById("total").value = suma();
});
// =============
$("#comp-p2").click(function () {
$("#cont-p2").clone().appendTo(".derecha");
document.getElementById("total").value = suma();
});
// =============
$("#comp-p3").click(function () {
$("#cont-p3").clone().appendTo(".derecha");
document.getElementById("total").value = suma();
});
});
Here it is working:
Added code to deal with the removal of elements also.
// Script for clone the div´s
$(document).ready(function() {
$("#comp-p1").click(function() {
$("#cont-p1").clone().appendTo(".derecha");
displaySuma();
});
// =============
$("#comp-p2").click(function() {
$("#cont-p2").clone().appendTo(".derecha");
displaySuma();
});
// =============
$("#comp-p3").click(function() {
$("#cont-p3").clone().appendTo(".derecha");
displaySuma();
});
});
const getParent = (match, node) => (node.matches(match)) ? node : getParent(match, node.parentNode);
// Deal with remove
document.addEventListener('click', (event) => {
let target = event.target;
if (target.matches('.bbp')) {
restar();
restardos();
getParent('.derecha', target).removeChild(target.parentNode);
displaySuma();
}
})
// New Script for sum inputs
const displaySuma = () => document.getElementById("total").value = suma();
const suma = function() {
let x = Array.from(document.querySelectorAll(".derecha div .add-prod"));
let sum = 0;
for (var i = 0; i < x.length; i++) {
sum += parseFloat(x[i].value);
}
console.log(sum);
return sum;
}
//console.log(suma());
document.getElementById("total").value = suma();
body {
margin: 0 auto;
color: #323232;
width: 100%;
height: 100%;
line-height: 1.5;
font-family: 'Roboto', serif
}
#container {
width: 500px;
margin: 0 auto
}
#container p {
display: inline-block;
margin-top: 20px
}
span {
font-weight: bold;
text-decoration: underline
}
#productos {
display: none
}
.img-prod {
display: inline-block;
float: left;
background: #000;
margin-right: 10px
}
.img-prod img {
width: 100%;
height: auto;
max-width: 70px;
display: block;
border: 0
}
#comp-p1,
#comp-p2,
#comp-p3 {
width: 120px;
height: 30px;
margin-top: 15px;
background: green;
padding: 10px 0 5px;
text-align: center;
vertical-align: middle;
color: #fff;
cursor: pointer
}
.derecha {
border: solid 1px #999;
max-height: 400px;
width: 350px;
margin: 0 auto;
text-align: center;
padding: 10px 0;
overflow-y: auto;
float: right
}
#producto-1,
#producto-2,
#producto-3 {
display: inline-block;
width: 220px;
padding: 10px;
float: left;
text-align: left;
font-size: .9em;
margin-right: 5px
}
#producto-1 {
background: green;
color: #fff
}
#producto-2 {
background: #add8e6;
color: #000
}
#producto-3 {
background: #666;
color: #fff
}
.cont-p {
display: inline-block;
margin: 7px auto;
line-height: 1
}
.bbp {
display: inline-block;
float: right;
width: 24px;
height: 24px;
text-align: center;
background: red;
color: #fff;
margin-left: 5px;
line-height: 1.5;
cursor: pointer
}
.cont-num {
float: left;
width: 24px;
height: 24px;
margin: 20px 5px 0 18px;
padding: 4px 3px 3px;
background: red;
text-align: center;
font-size: 16px;
font-family: Arial, sans-serif;
color: #fff
}
#mostrar {
display: none
}
#mostrar {
width: 100px;
margin: 70px 0 0;
padding: 10px;
text-align: center;
background: grey;
color: #fff;
cursor: pointer
}
/* ==== Style of Sume ==== */
.derecha input {
width: 40px;
display: block;
margin: 0 auto 10px 0;
padding: 2px 0;
background: #f2f2f2;
border: none;
border: 1px solid #000;
text-align: center
}
#cont-resultado {
text-align: center;
width: 110px;
margin-top: 70px;
background: grey;
padding: 5px 10px 10px;
color: #fff
}
#cont-resultado input {
display: inline-block;
margin: 10px auto;
background: #fff;
color: #000;
border: 1px solid #000;
padding: 8px 0
}
#cont-resultado p {
display: inline-block;
text-decoration: none;
color: #fff;
background: grey;
padding: 8px 10px;
cursor: pointer
}
#total {
display: block;
width: 80px;
text-align: center
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="container">
<div id="productos">
<!-- =============== -->
<div id="cont-p1" class="cont-p">
<div id="producto-1">
<div class="img-prod"><img src="https://upload.wikimedia.org/wikipedia/commons/3/39/Lichtenstein_img_processing_test.png"> </div>cont-p1 cloned!<br><br>Input Value = 1</div>
<input class="add-prod" type="num" value="1">
<div class="bbp">X</div>
</div>
<!-- =============== -->
<div id="cont-p2" class="cont-p">
<div id="producto-2">
<div class="img-prod"><img src="https://upload.wikimedia.org/wikipedia/commons/3/39/Lichtenstein_img_processing_test.png"></div>
cont-p2 cloned!<br><br>Input Value = 1</div>
<input class="add-prod" type="num" value="1">
<div class="bbp">X</div>
</div>
<!-- =============== -->
<div id="cont-p3" class="cont-p">
<div id="producto-3">
<div class="img-prod"><img src="https://upload.wikimedia.org/wikipedia/commons/3/39/Lichtenstein_img_processing_test.png"></div>
cont-p3 cloned!<br><br>Input Value = 198</div>
<input class="add-prod" type="num" value="198">
<div class="bbp">X</div>
</div>
<!-- =============== -->
</div>
<!-- // productos -->
<div class="derecha"></div>
<div id="comp-p1" onClick="clickME();clickME2();">Clone 1</div>
<div id="comp-p2" onClick="clickME();clickME2();">Clone 2</div>
<div id="comp-p3" onClick="clickME();clickME2();">Clone 3</div>
<div class="cont-num" id="clicks">0</div>
<div class="cont-num" id="clicksdos">0</div>
<div id="cont-resultado">
<span>RESULT:</span><br>
<input name="total" id="total">
<br>Is the sum of the cloned divs
<!--<p id='sumup'>Ver total</p>-->
</div>
<p><span>NOTE:</span><br>Here we are looking for only the cloned inputs can be sumed (and see the result in the box color gray).<br><br>The problem is that the current script does not apply a sume of the cloned inputs only... it adds ALL the inputs presents
in the html...<br><br>So (1), how do you sum only the cloned inputs, ignoring those that are outside...?<br><br>And (2) also, how to subtract from the total result all the cloned divs that are deleted...?</p>
</div>
<!-- // container -->
<script>
// Script that adds and subtracts the clicks
var clicks = 0;
function clickME() {
clicks += 1;
document.getElementById("clicks").innerHTML = clicks
}
var clicksdos = 0;
function clickME2() {
clicksdos += 1;
document.getElementById("clicksdos").innerHTML = clicksdos;
if (clicksdos === 1) {
document.getElementById("cont-resultado").style.display = "block";
}
}
if (clicksdos === 0) {
document.getElementById("cont-resultado").style.display = "none";
}
function restar() {
if (clicks > 0) clicks -= 1;
document.getElementById("clicks").innerHTML = clicks;
}
function restardos() {
if (clicksdos > 0) clicksdos -= 1;
document.getElementById("clicksdos").innerHTML = clicksdos;
if (clicksdos === 0) {
document.getElementById("cont-resultado").style.display = "none";
}
}
</script>

Categories

Resources