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

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>

Related

I'm making a flashcard using JS and i encounteres a problem when i click the save button the card appears but after that there is problem?

I am making an flashcard using javascript and everything is working fine but when I press the save button to save the card there is error. it should display the question and after a click event it should show the answer of that card clicked but there is an error. also my browser storing also doesn't work.
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: , sans-serif;
font-size: 1rem;
background: #092d4a;
}
button {
padding: 8px;
outline: none;
cursor: pointer;
border: 1px solid #092d4a;
border-radius: 5px;
}
button:hover {
background-color: #092d4a;
color: white;
}
.container {
width: 95%;
margin: auto;
}
.nav {
display: flex;
justify-content: space-between;
width: 100%;
margin: auto;
padding: 20px 0;
}
.nav button {
font-family: inherit;
}
.create-card {
display: none;
width: 380px;
margin: auto;
padding: 20px;
margin-top: 10px;
border-radius: 5px;
background: whitesmoke;
box-shadow: 0px 2px 4px 0px rgba(0, 0, 0, 0.5);
}
.create-card textarea {
width: 100%;
border-radius: 5px;
font-family: inherit;
border: 2px solid #092d4a;
}
.create-card button {
width: fit-content;
border: 2px solid #092d4a;
}
.flashcards {
display: flex;
justify-content: flex-start;
align-items: flex-start;
flex-wrap: wrap;
width: 100%;
margin: auto;
margin-top: 20px;
padding: 0px 17px;
}
.flashcard {
width: 370px;
height: 200px;
word-wrap: break-word;
margin: 15px;
background: #fff;
/* box-shadow: 0px 2px 6px 0px rgba(0, 0, 0, 0.9); */
box-shadow: 0px 2px 4px 0px rgba(255, 255, 255, 0.5);
}
.flashcard h2 {
font-size: 1rem;
}
#media(max-width:768px) {
.flashcard {
margin: auto;
}
.flashcard {
margin-top: 15px;
margin-bottom: 15px;
}
}
#media(max-width:480px) {
.create-card {
width: 100%;
}
.flashcard {
width: 100%;
}
}
<header>
<div class="container">
<div class="nav">
<h1> Saved Flashcards</h1>
<button class="btn1">Add New Card</button>
</div>
</div>
</header>
<div class="container">
<div class="create-card">
<p>
<h2 style="color: black;text-align: center;">Create Flashcard</h2>
</p>
<p>
<label for="text">Question</label><br>
<textarea id="question" placeholder="please enter your question here....."></textarea>
</p>
<p>
<label for="text">Answer</label><br>
<textarea id="answer" placeholder="please place your answer here...."></textarea>
</p>
<br>
<div>
<button class="btn2" onclick="saveFlashcard()">Save</button>
<button class="btn3">Close</button>
</div>
</div>
</div>
<div class="container">
<div class="flashcards" id="flashcards"></div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="brain.js">
const flashcards = document.getElementsByClassName("flashcards")[0];
const createCard = document.getElementsByClassName("create-card")[0];
const question = document.getElementById("question");
const answer = document.getElementById("answer");
// if (localStorage.getItem("stored") == null) {
// localStorage.setItem("stored", [])
// };
// var test = JSON.parse(localStorage.getItem("stored"));
// var div = document.createElement("div");
// var h2_question = document.createElement("h2");
// var h2_answer = document.createElement("h2");
// div.className = "flashcard";
// h2_question.setAttribute("style", "border-top:1px solid blue; padding:15px; margin-top:30px");
// h2_question.innerHTML = localStorage.getItem("test");
// h2_answer.setAttribute("style", "text-align:center; display:none; color:Blue");
// h2_answer.innerHTML = localStorage.getItem("test");
// div.appendChild(h2_question);
// div.appendChild(h2_answer);
// flashcards.insertAdjacentElement("beforeend", div);
$(".btn1").on("click", function() {
$(".create-card").show();
});
$(".btn3").on("click", function() {
$(".create-card").hide();
});
function saveFlashcard() {
var div = document.createElement("div");
var h2_question = document.createElement("h2");
var h2_answer = document.createElement("h2");
div.className = "flashcard";
h2_question.setAttribute("style", "border-top:1px solid blue; padding:15px; margin-top:30px");
h2_question.innerHTML = question.value;
h2_answer.setAttribute("style", "text-align:center; display:none; color:Blue");
h2_answer.innerHTML = answer.value;
// $(".div").on("click", function() {
// $(".h2_question").show();
// });
div.appendChild(h2_question);
div.appendChild(h2_answer);
$("div").on("click", function() {
if (h2_answer.style.display == "none") {
h2_answer.style.display = "block";
} else {
h2_answer.style.display = "none";
}
});
div.addEventListener("dblclick", function() {
div.remove();
});
flashcards.insertAdjacentElement("beforeend", div);
question.value = '';
answer.value = '';
// var test = JSON.parse(localStorage.getItem("stored"));
// test.push(JSON.stringify([question.value, answer.value]));
};
</script>

JavaScript not working properly in a To-Do List Project

So I'm working on this simple project. It's a To-Do List. Every task has to buttons, namely, done and delete (These are images). And there are two divisions, one will store the pending tasks and the other will stored the completed tasks.
I want that when the user clicks on the done button (tick image) the task should be removed from the "Pending Tasks" division and shifted to the "Completed Tasks" division. I tried to add this functionality by adding an event listener to the images. The event listens for a single click. But the code is not working properly. For the first task, I've to click twice to remove it. The same is the case with other tasks as well. Which means every single task is added twice to the "Completed Tasks" division.
Also, I've added functionality to add new tasks. But the buttons (images) don't work on these new tasks. Basically, event listening is not working on them. Kindly help with the issue. I've added the code below.
(I've not added any functionality for deletion)
var completedTasks = document.querySelector(".Completed-Tasks");
var pendingTasks = document.querySelector(".Pending-Tasks");
var addTaskButton = document.querySelector(".Add-Task-Button");
var doneButtons = document.querySelectorAll(".Tick");
var deleteButtons = document.querySelectorAll(".Cross");
doneButtons.forEach(checkClickEvent);
console.log(doneButtons.length);
function checkClickEvent(button, index) {
button.addEventListener("click", function() {
let task = button.parentNode.parentNode;
pendingTasks.removeChild(pendingTasks.childNodes[index]);
let doneTaskHTML = `<div class="Task Done"><p class="Task-Text">${task.children[0].textContent}</p><div class="Task-Operations"><img src="./Cross.png" alt="Delete" class="Operation"></div></div>`;
completedTasks.insertAdjacentHTML("beforeend", doneTaskHTML);
});
}
addTaskButton.addEventListener("click", function(event) {
event.preventDefault();
let newTaskText = document.querySelector(".Add-Task-Input");
if (newTaskText.value != "") {
let newTaskHTML = `<div class="Task"><p class="Task-Text">${newTaskText.value}</p><div class="Task-Operations"><img src="./Tick.png" alt="Done" class="Operation Tick"><img src="./Cross.png" alt="Delete" class="Operation Cross"></div></div>`;
pendingTasks.insertAdjacentHTML("beforeend", newTaskHTML);
newTaskText.value = "";
}
});
#import url('https://fonts.googleapis.com/css2?family=Poppins&display=swap');
* {
margin: 0px;
padding: 0px;
box-sizing: border-box;
font-family: "Poppins";
}
body {
background: #EDF2F4;
display: flex;
align-items: center;
justify-content: center;
flex-direction: column;
min-height: 100vh;
}
.Header {
background: #2B2D42;
color: #FFFFFF;
max-width: 500px;
width: 100%;
padding: 15px;
margin-bottom: 20px;
}
.Heading {
font-size: 25px;
text-align: center;
}
.Tasks-Space {
background: #8D99AE;
max-width: 500px;
width: 100%;
padding: 15px;
position: relative;
}
.Add-Task {
position: relative;
width: 100%;
}
.Add-Task-Input {
outline: none;
border: none;
padding: 5px 10px;
width: 100%;
font-size: 16px;
}
.Add-Task-Button {
outline: none;
border: none;
width: 100%;
padding: 5px 10px;
margin-top: 15px;
font-size: 16px;
cursor: pointer;
background: #D90429;
color: #FFFFFF;
}
.Add-Task-Button:hover {
background: #EF233C;
color: #FFFFFF;
}
.Tasks-Space-Heading {
margin-top: 15px;
padding: 5px 10px;
background: #2B2D42;
color: #FFFFFF;
}
.Pending-Tasks {
margin-top: 15px;
}
.Completed-Tasks {
margin-top: 15px;
}
.Task {
background: #FFFFFF;
padding: 5px 10px;
display: flex;
align-items: center;
justify-content: space-between;
}
.Task-Operations {
display: flex;
align-items: center;
}
.Operation {
height: 20px;
margin-left: 10px;
cursor: pointer;
}
.Done {
text-decoration: line-through;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>To-Do List</title>
<link rel="stylesheet" href="./style.css">
</head>
<body>
<div class="Header">
<p class="Heading">TO-DO LIST</p>
</div>
<div class="Tasks-Space">
<div class="Add-Task">
<input type="text" placeholder="Enter your task here" class="Add-Task-Input">
<button class="Add-Task-Button">Add Task</button>
</div>
<p class="Tasks-Space-Heading">Pending Tasks</p>
<div class="Pending-Tasks">
<div class="Task">
<p class="Task-Text">Make a pie</p>
<div class="Task-Operations">
<img src="./Tick.png" alt="Done" class="Operation Tick">
<img src="./Cross.png" alt="Delete" class="Operation Cross">
</div>
</div>
<div class="Task">
<p class="Task-Text">Play Minecraft</p>
<div class="Task-Operations">
<img src="./Tick.png" alt="Done" class="Operation Tick">
<img src="./Cross.png" alt="Delete" class="Operation Cross">
</div>
</div>
</div>
<p class="Tasks-Space-Heading">Completed Tasks</p>
<div class="Completed-Tasks"></div>
</div>
<script src="./main.js"></script>
</body>
</html>
Instead of pendingTasks.removeChild(pendingTasks.childNodes[index]); do task.remove(); since you already have the node that you want to remove. here is the reference to remove() function.
Also added document.querySelectorAll(".Tick").forEach(checkClickEvent); in add task click handler. This should add event listener to newly added tasks as well.
Edited
The solution did work but there was a slight problem. When we are adding event listeners to the new tasks using document.querySelectorAll(".Tick").forEach(checkClickEvent);, multiple event listeners are getting added to the existing tasks. To avoid this simply reinitialize the HTML inside the division. This can be done using pendingTasks.innerHTML = pendingTasks.innerHTML;. This code will remove all the existing event listeners on any element inside the division. Note that this code has to be used before adding event listeners again.
var completedTasks = document.querySelector(".Completed-Tasks");
var pendingTasks = document.querySelector(".Pending-Tasks");
var addTaskButton = document.querySelector(".Add-Task-Button");
var doneButtons = document.querySelectorAll(".Tick");
var deleteButtons = document.querySelectorAll(".Cross");
doneButtons.forEach(checkClickEvent);
console.log(doneButtons.length);
function checkClickEvent(button, index) {
button.addEventListener("click", function() {
let task = button.parentNode.parentNode;
task.remove();
let doneTaskHTML = `<div class="Task Done"><p class="Task-Text">${task.children[0].textContent}</p><div class="Task-Operations"><img src="./Cross.png" alt="Delete" class="Operation"></div></div>`;
completedTasks.insertAdjacentHTML("beforeend", doneTaskHTML);
});
}
addTaskButton.addEventListener("click", function(event) {
event.preventDefault();
let newTaskText = document.querySelector(".Add-Task-Input");
if (newTaskText.value != "") {
let newTaskHTML = `<div class="Task"><p class="Task-Text">${newTaskText.value}</p><div class="Task-Operations"><img src="./Tick.png" alt="Done" class="Operation Tick"><img src="./Cross.png" alt="Delete" class="Operation Cross"></div></div>`;
pendingTasks.insertAdjacentHTML("beforeend", newTaskHTML);
newTaskText.value = "";
pendingTasks.innerHTML = pendingTasks.innerHTML; // Re-initialize
document.querySelectorAll(".Tick").forEach(checkClickEvent); // Adding event listeners again
}
});
#import url('https://fonts.googleapis.com/css2?family=Poppins&display=swap');
* {
margin: 0px;
padding: 0px;
box-sizing: border-box;
font-family: "Poppins";
}
body {
background: #EDF2F4;
display: flex;
align-items: center;
justify-content: center;
flex-direction: column;
min-height: 100vh;
}
.Header {
background: #2B2D42;
color: #FFFFFF;
max-width: 500px;
width: 100%;
padding: 15px;
margin-bottom: 20px;
}
.Heading {
font-size: 25px;
text-align: center;
}
.Tasks-Space {
background: #8D99AE;
max-width: 500px;
width: 100%;
padding: 15px;
position: relative;
}
.Add-Task {
position: relative;
width: 100%;
}
.Add-Task-Input {
outline: none;
border: none;
padding: 5px 10px;
width: 100%;
font-size: 16px;
}
.Add-Task-Button {
outline: none;
border: none;
width: 100%;
padding: 5px 10px;
margin-top: 15px;
font-size: 16px;
cursor: pointer;
background: #D90429;
color: #FFFFFF;
}
.Add-Task-Button:hover {
background: #EF233C;
color: #FFFFFF;
}
.Tasks-Space-Heading {
margin-top: 15px;
padding: 5px 10px;
background: #2B2D42;
color: #FFFFFF;
}
.Pending-Tasks {
margin-top: 15px;
}
.Completed-Tasks {
margin-top: 15px;
}
.Task {
background: #FFFFFF;
padding: 5px 10px;
display: flex;
align-items: center;
justify-content: space-between;
}
.Task-Operations {
display: flex;
align-items: center;
}
.Operation {
height: 20px;
margin-left: 10px;
cursor: pointer;
}
.Done {
text-decoration: line-through;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>To-Do List</title>
<link rel="stylesheet" href="./style.css">
</head>
<body>
<div class="Header">
<p class="Heading">TO-DO LIST</p>
</div>
<div class="Tasks-Space">
<div class="Add-Task">
<input type="text" placeholder="Enter your task here" class="Add-Task-Input">
<button class="Add-Task-Button">Add Task</button>
</div>
<p class="Tasks-Space-Heading">Pending Tasks</p>
<div class="Pending-Tasks">
<div class="Task">
<p class="Task-Text">Make a pie</p>
<div class="Task-Operations">
<img src="./Tick.png" alt="Done" class="Operation Tick">
<img src="./Cross.png" alt="Delete" class="Operation Cross">
</div>
</div>
<div class="Task">
<p class="Task-Text">Play Minecraft</p>
<div class="Task-Operations">
<img src="./Tick.png" alt="Done" class="Operation Tick">
<img src="./Cross.png" alt="Delete" class="Operation Cross">
</div>
</div>
</div>
<p class="Tasks-Space-Heading">Completed Tasks</p>
<div class="Completed-Tasks"></div>
</div>
<script src="./main.js"></script>
</body>
</html>
Try using this code
// Create a "close" button and append it to each list item
var myNodelist = document.getElementsByTagName("LI");
var i;
for (i = 0; i < myNodelist.length; i++) {
var span = document.createElement("SPAN");
var txt = document.createTextNode("\u00D7");
span.className = "close";
span.appendChild(txt);
myNodelist[i].appendChild(span);
}
// Click on a close button to hide the current list item
var close = document.getElementsByClassName("close");
var i;
for (i = 0; i < close.length; i++) {
close[i].onclick = function(data) {
var div = this.parentElement;
div.style.display = "none";
var data = div.innerText;
var list = document.getElementById("list");;
var firstname = div.value;
var entry = document.createElement('li');
entry.appendChild(document.createTextNode(data));
list.appendChild(entry);
}
}
// Add a "checked" symbol when clicking on a list item
var list = document.querySelector('ul');
list.addEventListener('click', function(ev) {
if (ev.target.tagName === 'LI') {
ev.target.classList.toggle('checked');
}
}, false);
// Create a new list item when clicking on the "Add" button
function newElement() {
var li = document.createElement("li");
var inputValue = document.getElementById("myInput").value;
var t = document.createTextNode(inputValue);
li.appendChild(t);
if (inputValue === '') {
alert("You must write something!");
} else {
document.getElementById("myUL").appendChild(li);
}
document.getElementById("myInput").value = "";
var span = document.createElement("SPAN");
var txt = document.createTextNode("\u00D7");
span.className = "close";
span.appendChild(txt);
li.appendChild(span);
for (i = 0; i < close.length; i++) {
close[i].onclick = function() {
var div = this.parentElement;
div.style.display = "none";
}
}
}
body {
margin: 0;
min-width: 250px;
font-family: arial;
}
/* Include the padding and border in an element's total width and height */
* {
box-sizing: border-box;
}
/* Remove margins and padding from the list */
ul {
margin: 0;
padding: 0;
}
/* Style the list items */
ul li {
cursor: pointer;
position: relative;
padding: 12px 8px 12px 40px;
list-style-type: none;
font-size: 18px;
transition: 0.2s;
border-bottom: 1px solid #eee;
margin-top: -1px;
/* make the list items unselectable */
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
/* When clicked on, add a background color and strike out text */
ul li.checked {
background: #888;
color: #fff;
text-decoration: line-through;
}
/* Add a "checked" mark when clicked on */
ul li.checked::before {
content: '';
position: absolute;
border-color: #fff;
border-style: solid;
border-width: 0 2px 2px 0;
top: 10px;
left: 16px;
transform: rotate(45deg);
height: 15px;
width: 7px;
}
/* Style the close button */
.close {
position: absolute;
right: 0;
top: 0;
padding: 12px 16px 12px 16px;
}
.close:hover {
background-color: #f44336;
color: white;
}
/* Style the header */
.header {
background-color: #f44336;
padding: 30px 40px;
color: white;
text-align: center;
}
/* Clear floats after the header */
.header:after {
content: "";
display: table;
clear: both;
}
/* Style the input */
input {
margin: 0;
border: none;
border-radius: 0;
width: 75%;
padding: 10px;
float: left;
font-size: 16px;
}
input[type=text] {
outline: 0;
background: #eee;
border: 0;
transition: all .2s;
}
input[type=text]:focus {
background: #fff;
box-shadow: 0 3px 1px -2px rgba(0, 0, 0, 0.2), 0 2px 2px 0 rgba(0, 0, 0, 0.14), 0 1px 5px 0 rgba(0, 0, 0, 0.12);}
/* Style the "Add" button */
.addBtn {
padding: 10px;
width: 25%;
background: #d9d9d9;
color: #555;
float: left;
text-align: center;
font-size: 16px;
cursor: pointer;
transition: 0.3s;
border-radius: 0;
}
.addBtn:hover {
background-color: #bbb;
}
<script src="https://code.jquery.com/jquery-3.5.1.js" integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc=" crossorigin="anonymous"></script>
<div id="myDIV" class="header">
<h2 style="margin:5px">My To Do List</h2>
<input type="text" id="myInput" placeholder="Title..." autocomplete="off">
<span onclick="newElement()" class="addBtn">Add</span>
</div>
<ul id="myUL">
<li>Hit the gym</li>
<li>Pay bills</li>
<li>Meet George</li>
<li>Buy eggs</li>
<li>Read a book</li>
<li>Organize office</li>
</ul>
<p style="padding-left: 30px;">Completed Tasks</p>
<ul id="list"></ul>

Make only 5 results to be visible in a search bar at a time

I have an search bar which is working perfectly.
But getting an issue. I want only 5 results to be vsible at a time and other results should be seen by sliding from the slider.
For example if it contains 10 results. Then is shoould show ony 5 on searching and to see other user can sllide from the slidebar....
here is my code
function filterFunction() {
let isInputAvail = false;
var input, filter, ul, li, a, i;
input = document.getElementById("myInput");
filter = input.value.toLowerCase();
if (filter.length > 0) {
document.getElementById("myDropdown").classList.add("show");
} else {
document.getElementById("myDropdown").classList.remove("show");
}
div = document.getElementById("myDropdown");
a = div.getElementsByTagName("a");
for (i = 0; i < a.length; i++) {
txtValue = a[i].innerText;
if (txtValue.toLowerCase().indexOf(filter) > -1) {
isInputAvail = true;
a[i].style.display = "block";
} else {
a[i].style.display = "none";
}
}
if (!isInputAvail) {
document.getElementById("noMatches").classList.add('show');
} else {
document.getElementById("noMatches").classList.remove('show');
}
}
.div {
display: none;
}
.dropbtn {
padding: 16px;
font-size: 16px;
border: none;
cursor: pointer;
border-radius: 25px;
}
#myInput {
box-sizing: border-box;
background-position: 14px 12px;
background-repeat: no-repeat;
font-size: 16px;
padding: 14px 20px 12px 45px;
border: 5px solid #ddd;
border-radius: 25px;
}
#myInput:focus {
outline: 4px solid #f2f2f2;
border-color: #171313;
}
.dropdown {
position: relative;
display: inline-block;
}
.dropdown-content {
display: none;
position: absolute;
background-color: #f6f6f6;
min-width: 230px;
overflow: auto;
border: none;
z-index: 1;
border-radius: 25px;
}
.dropdown-content a {
color: black;
padding: 12px 16px;
text-decoration: none;
display: block;
}
.dropdown a:hover {
background-color: #ddd;
}
.show {
display: block;
}
<div class="dropdown">
<input type="text" class="dropbtn" placeholder="Search Here..." id="myInput" onInput="filterFunction()">
<div id="myDropdown" class="dropdown-content">
Result 1
Result 2
Result 3
Result 4
Result 5
Result 6
Result 7
Result 8
Result 9
Result 10
Result 11
Result 12
Result 13
Result 14
Result 15
</div>
<div id="noMatches" class="dropdown-content">
No Matches
</div>
</div>
Here i want that when i write result then all the matching result is shown but that show a huge list. I want to make it to show ony 5 result and there should be a slidebar at right side from which on sliding other results can be seen.
Hope you got my point.
Thanks in advance.
Check out this snippet:
function filterFunction() {
let isInputAvail = false;
var input, filter, ul, li, a, i;
input = document.getElementById("myInput");
filter = input.value.toLowerCase();
if (filter.length > 0) {
document.getElementById("myDropdown").classList.add("show");
} else {
document.getElementById("myDropdown").classList.remove("show");
}
div = document.getElementById("myDropdown");
a = div.getElementsByTagName("a");
for (i = 0; i < a.length; i++) {
txtValue = a[i].innerText;
if (txtValue.toLowerCase().indexOf(filter) > -1) {
isInputAvail = true;
a[i].style.display = "block";
} else {
a[i].style.display = "none";
}
}
if (!isInputAvail) {
document.getElementById("noMatches").classList.add('show');
} else {
document.getElementById("noMatches").classList.remove('show');
}
}
.div {
display: none;
}
.dropbtn {
padding: 16px;
font-size: 16px;
border: none;
cursor: pointer;
border-radius: 25px;
}
#myInput {
box-sizing: border-box;
background-position: 14px 12px;
background-repeat: no-repeat;
font-size: 16px;
padding: 14px 20px 12px 45px;
border: 5px solid #ddd;
border-radius: 25px;
}
#myInput:focus {
outline: 4px solid #f2f2f2;
border-color: #171313;
}
.dropdown {
position: relative;
display: inline-block;
}
.dropdown-content {
max-height: 215px;
display: none;
position: absolute;
background-color: #f6f6f6;
min-width: 230px;
overflow-y: scroll;
border: none;
z-index: 1;
border-radius: 25px;
}
.dropdown-content a {
color: black;
padding: 12px 16px;
text-decoration: none;
display: block;
}
.dropdown a:hover {
background-color: #ddd;
}
.show {
display: block;
}
<!DOCTYPE html>
<html lang="en">
<head>
<title>Test</title>
</head>
<body>
<div class="dropdown">
<input type="text" class="dropbtn" placeholder="Search Here..." id="myInput" onInput="filterFunction()">
<div id="myDropdown" class="dropdown-content">
Result 1
Result 2
Result 3
Result 4
Result 5
Result 6
Result 7
Result 8
Result 9
Result 10
Result 11
Result 12
Result 13
Result 14
Result 15
</div>
<div id="noMatches" class="dropdown-content">
No Matches
</div>
</div>
</body>
</html>
I have limited maximum height of .dropdown-content using max-height property and set vertical overflow to scroll using overflow-y: scroll;. Removed overflow: auto from .dropdown-content.
Don't use IDs, programming should be writing reusable code.
To show the dropdowns or to switch the list/no-matches, use two classes on the parent element ("hasvalue" and "nomatch"), the rest is all pure CSS and the :focus selector
Use CSS max-height to limit the height of your overflow element
UI/UX tip: half-cut the last list word, to additionally give the user a clue that there's more items in the scrollable element.
function dropdown(EL) {
const EL_input = EL.querySelector(".dropdown-input");
const ELS_li = EL.querySelectorAll(".dropdown-box--list a");
const filter = () => {
const val = EL_input.value.trim().toLowerCase();
const fil = [...ELS_li].filter(el => {
const match = el.textContent.trim().toLowerCase().includes(val);
el.classList.toggle("hide", !match);
return match;
});
EL.classList.toggle("hasvalue", val.length);
EL.classList.toggle("nomatch", val.length && !fil.length);
};
EL_input.addEventListener("input", filter);
EL_input.addEventListener("focus", filter);
ELS_li.forEach(el => el.addEventListener("mousedown", () => {
EL_input.value = el.textContent.trim()
}));
}
document.querySelectorAll(".dropdown").forEach(el => dropdown(el));
/* QuickReset */ * {margin: 0; box-sizing: border-box;}
/* DROPDOWN COMPONENT */
.dropdown {
--item-height: 30px;
--visible: 5;
font-family: sans-serif;
position: relative;
display: inline-block;
}
.dropdown-input {
padding: 16px;
font-size: 16px;
border: none;
cursor: pointer;
font-size: 16px;
padding: 15px 20px;
border: 5px solid #ddd;
border-radius: 25px;
background: #fff;
}
.dropdown-input:focus {
outline: none;
border-color: #000;
}
.dropdown.hasvalue .dropdown-input:focus {
border-bottom: 1px solid #ddd;
border-radius: 25px 25px 0 0;
}
.dropdown-box {
display: none;
position: absolute;
top: 100%;
z-index: 1;
min-width: 100%;
overflow: auto;
border-radius: 0 0 10px 10px;
max-height: calc(var(--item-height) * var(--visible));
border: 5px solid #000;
border-top: 0;
}
.dropdown.hasvalue .dropdown-input:focus~.dropdown-box--list {
display: block;
}
.dropdown.nomatch .dropdown-input:focus~.dropdown-box--list {
display: none;
}
.dropdown.nomatch .dropdown-input:focus~.dropdown-box--nomatch {
display: block !important;
}
.dropdown-box a {
display: flex;
align-items: center;
padding: 7px 20px;
min-height: var(--item-height);
color: black;
text-decoration: none;
transition: background 0.24s;
}
.dropdown-box a.hide {
display: none;
}
.dropdown-box a:hover {
background-color: #acf;
}
.dropdown-box::-webkit-scrollbar {
width: 10px;
height: 10px;
}
.dropdown-box::-webkit-scrollbar-track {
background: transparent;
border-radius: 10px;
}
.dropdown-box::-webkit-scrollbar-thumb {
background-color: #000;
border-radius: 10px;
}
<div class="dropdown">
<input type="text" class="dropdown-input" autocomplete="off" placeholder="🔍︎ Search...">
<div class="dropdown-box dropdown-box--list">
Result 1
Result 2
Result 3
Result 4
Result 5
Result 6
Result 7
Result 8
Result 9
Result 10
Result 11
Result 12
Result 13
Result 14
Result 15
</div>
<div class="dropdown-box dropdown-box--nomatch">
<i>No Matches</i>
</div>
</div>
<div class="dropdown">
<input type="text" class="dropdown-input" autocomplete="off" placeholder="🔍︎ Yet another...">
<div class="dropdown-box dropdown-box--list">
Lorem
Ipsum
Dolor sit amet
Lorem ut florem
</div>
<div class="dropdown-box dropdown-box--nomatch">
<i>No Matches</i>
</div>
</div>

How to fit elements at slider container

I work with statick creation elements, and for this i need to have slider.
I just create slider, but elements are not fit in to slider container.
Example:
var htmlElements;
var userName = "Jonny Programmer"
var id = "6656"
function createUserCard() {
htmlElements = `<div class="user-card">
<img src="https://source.unsplash.com/user/erondu" class="userImage" />
<div class="info">
<div class="name">${userName}</div>
<div class="handle">
<div class="idPersone">${id}</div>
</div>
</div>
</div>`
$('.cardsCreation').append(htmlElements);
}
$('#plus-button').on('click', function () {
createUserCard();
});
(function () {
var sliderImages = document.querySelectorAll('.image'),
arrowLeft = document.querySelector('#left-arrow'),
arrowRight = document.querySelector('#right-arrow'),
currentImg = 0;
function initSlider() {
resetSlider();
sliderImages[0].style.display = 'block';
}
function resetSlider() {
for (var i = 0; i < sliderImages.length; i++) {
sliderImages[i].style.display = 'none';
}
}
function toLeft() {
resetSlider();
sliderImages[currentImg - 1].style.display = 'block';
currentImg--;
}
function toRight() {
resetSlider();
sliderImages[currentImg + 1].style.display = 'block';
currentImg++;
}
arrowLeft.addEventListener('click', function () {
if (currentImg === 0) {
currentImg = sliderImages.length;
}
toLeft();
});
arrowRight.addEventListener('click', function () {
if (currentImg === sliderImages.length - 1) {
currentImg = -1;
}
toRight();
});
initSlider();
})();
.user-card, userImage {
box-shadow: 0px 2px 5px 0 rgba(0,0,0,0.25);
}
.user-card {
margin: 12px;
padding: 10px 10px 10px 10px;
border-radius: 12px;
width: 160px;
text-align: center;
float: left;
background-color: #fff;
}
.userImage {
border-radius: 50%;
height: 140px;
width: 140px;
border: 5px solid #eee;
}
.name {
font-size: 20px;
margin: 5px;
font-weight: bold;
}
.progress {
color: #25af53;
font-size: 48px;
}
#plus-button {
width: 55px;
height: 55px;
border-radius: 50%;
background: #428bca;
position: absolute;
top: 33%;
margin-left: 20px;
cursor: pointer;
box-shadow: 0px 2px 5px #666;
border: none;
outline: none;
}
.plus {
color: white;
position: absolute;
top: 0;
display: block;
bottom: 0;
left: 0;
right: 0;
text-align: center;
padding: 0;
margin: 0;
line-height: 55px;
font-size: 38px;
font-family: 'Roboto';
font-weight: 300;
}
#plus-button:hover {
box-shadow: 0 6px 14px 0 #666;
transform: scale(1.05);
}
.wrapper {
position: relative;
}
.arrow {
cursor: pointer;
position: absolute;
width: 0;
height: 0;
border-style: solid;
top: 50%;
margin-top: 160px;
}
#left-arrow {
border-width: 50px 40px 50px 0;
border-color: transparent #000 transparent transparent;
left: 0;
margin-left: 25px;
}
#right-arrow {
border-width: 50px 0 50px 40px;
border-color: transparent transparent transparent #000;
right: 0;
margin-right: 25px;
}
.image {
background-size: cover;
background-position: center;
background-repeat: no-repeat;
}
.vertical-align-wrapper {
display: table;
overflow: hidden;
text-align: center;
}
.vertical-align-wrapper span {
display: table-cell;
vertical-align: middle;
font-size: 5rem;
color: #ffffff;
}
#media only screen and (max-width : 992px) {
.vertical-align-wrapper span {
font-size: 2.5rem;
}
#left-arrow {
border-width: 30px 20px 30px 0;
margin-left: 15px;
}
#right-arrow {
border-width: 30px 0 30px 20px;
margin-right: 15px;
}
.arrow {
margin-top: -30px;
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="wrapper">
<div id="left-arrow" class="arrow"></div>
<div id="slider">
<div class="image image-one">
<div class="vertical-align-wrapper">
<div class="cardsCreation"></div>
<button id="plus-button">
<p class="plus">+</p>
</button>
</div>
</div>
<div class="image image-two">
<div class="vertical-align-wrapper">
<span>Slide 2</span>
</div>
</div>
<div class="image image-three">
<div class="vertical-align-wrapper">
<span>Slide 3</span>
</div>
</div>
</div>
<div id="right-arrow" class="arrow"></div>
</div>
So as u can see affter tapping "+" i add new ellement in to html.
And from two sides i have arrows which are changing slider.
After tapping arrows go down, and this is not good.
And after i will reach limit of adding element in one slider it's add new element to new slider page.
What i want ex:
If you are using toggle of display CSS property that happened because it remove whole element from the DOM so, I suggest you to use visibility or opacity properties to done your task.

Add checkbox to price calculation

Currently my price output gets calculated based on the chosen quantity of an input field. I have been trying to add a checkbox to this calculation that, if checked, adds $5 to the total price. That being said, I haven't been very successful. In my understanding, there are two calculations going on:
I hit the increase/decrease button and it checks if the checkbox has been selected
I select the checkbox and it calculates the total price
This is the code I have so far:
function IncludePrice()
{
var IncludePrice=0;
var include = theForm.elements["include"];
if(include.checked==true)
{
IncludePrice=5;
}
return IncludePrice;
}
$(".incr-btn_mobile").on("click", function(e) {
var $button = $(this);
var oldValue = $button.parent().find('.quantity').val();
$button.parent().find('.incr-btn_mobile[data-action="decrease"]').removeClass('inactive');
if ($button.data('action') == "increase") {
var newVal = parseFloat(oldValue) + 1;
} else {
// Don't allow decrementing below 1
if (oldValue > 1) {
var newVal = parseFloat(oldValue) - 1;
} else {
newVal = 1;
$button.addClass('inactive');
}
}
$button.parent().find('.quantity').val(newVal);
var cakePrice = newVal;
var includep = IncludePrice();
var divobj = document.getElementById($button.attr('data-target'));
divobj.style.display = 'block';
divobj.innerHTML = "= $" + (cakePrice) * 7.99 + (includep);
e.preventDefault();
});
.bg {
width: 100%;
}
.column {
float: left;
width: 50%;
padding: 10px;
}
/* Clear floats after the columns */
.row:after {
content: "";
display: table;
clear: both;
}
.count-input_mobile {
position: relative;
max-width: 1000%;
max-width: 400px;
margin-top: 10px;
text-align: center;
}
.count-input_mobile input {
width: 100%;
height: 42px;
border: 1px solid #000
border-radius: 2px;
background: none;
text-align: center;
}
.count-input_mobile input:focus {
outline: none;
}
.count-input_mobile .incr-btn_mobile {
display: block;
position: absolute;
width: 30px;
height: 30px;
font-size: 26px;
font-weight: 300;
text-align: center;
line-height: 30px;
top: 50%;
right: 0;
margin-top: -15px;
text-decoration:none;
}
.count-input_mobile .incr-btn_mobile:first-child {
right: auto;
left: 0;
top: 46%;
}
.count-input_mobile.count-input-sm {
max-width: 125px;
}
.count-input_mobile.count-input-sm input {
height: 36px;
}
.count-input_mobile.count-input-lg {
max-width: 200px;
}
.count-input_mobile.count-input-lg input {
height: 70px;
border-radius: 3px;
}
.button_mobile {
border: 1px solid #000;
border-radius: 2px;
background: none;
padding: 10.5px;
width:100%;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
cursor: pointer;
margin-top:10px;
}
.sum_output {
background: none;
padding: 9.5px;
width:100%;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
cursor: pointer;
margin-top:10px;
}
.accordion_img {
width:200%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<div class="count-input_mobile space-bottom">
<a class="incr-btn_mobile" data-action="decrease" data-target="cleanse_drop_1" href="#">–</a>
<input class="quantity" id="ShowButton_value_1" type="text" name="quantity" value="1"/>
<a class="incr-btn_mobile" data-action="increase" data-target="cleanse_drop_1" href="#">+</a>
</div>
<label for='include' class="inlinelabel">Include Extra? ($5)</label>
<input type="checkbox" id="include" name='include' data-target="cleanse_drop_1" />
<div id="cleanse_drop_1" class="sum_output">= $7.99</div>
UPDATE:
I changed made some changes based on the feedback here, but this seems to break the increase/decrease field. Here is the code as is:
$(".incr-btn_mobile").on("click", function(e) {
var $button = $(this);
var oldValue = $button.parent().find('.quantity').val();
$button.parent().find('.incr-btn_mobile[data-action="decrease"]').removeClass('inactive');
if ($button.data('action') == "increase") {
var newVal = parseFloat(oldValue) + 1;
} else {
// Don't allow decrementing below 1
if (oldValue > 1) {
var newVal = parseFloat(oldValue) - 1;
} else {
newVal = 1;
$button.addClass('inactive');
}
}
$button.parent().find('.quantity').val(newVal);
var cakePrice = newVal;
var includep = theForm.elements.include.checked * 5;
var divobj = document.getElementById($button.attr('data-target'));
divobj.style.display = 'block';
divobj.innerHTML = "= $" + (cakePrice) * 7.99 + (includep);
e.preventDefault();
});
.bg {
width: 100%;
}
.column {
float: left;
width: 50%;
padding: 10px;
}
/* Clear floats after the columns */
.row:after {
content: "";
display: table;
clear: both;
}
.count-input_mobile {
position: relative;
max-width: 1000%;
max-width: 400px;
margin-top: 10px;
text-align: center;
}
.count-input_mobile input {
width: 100%;
height: 42px;
border: 1px solid #000
border-radius: 2px;
background: none;
text-align: center;
}
.count-input_mobile input:focus {
outline: none;
}
.count-input_mobile .incr-btn_mobile {
display: block;
position: absolute;
width: 30px;
height: 30px;
font-size: 26px;
font-weight: 300;
text-align: center;
line-height: 30px;
top: 50%;
right: 0;
margin-top: -15px;
text-decoration:none;
}
.count-input_mobile .incr-btn_mobile:first-child {
right: auto;
left: 0;
top: 46%;
}
.count-input_mobile.count-input-sm {
max-width: 125px;
}
.count-input_mobile.count-input-sm input {
height: 36px;
}
.count-input_mobile.count-input-lg {
max-width: 200px;
}
.count-input_mobile.count-input-lg input {
height: 70px;
border-radius: 3px;
}
.button_mobile {
border: 1px solid #000;
border-radius: 2px;
background: none;
padding: 10.5px;
width:100%;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
cursor: pointer;
margin-top:10px;
}
.sum_output {
background: none;
padding: 9.5px;
width:100%;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
cursor: pointer;
margin-top:10px;
}
.accordion_img {
width:200%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<div class="count-input_mobile space-bottom">
<a class="incr-btn_mobile" data-action="decrease" data-target="cleanse_drop_1" href="#">–</a>
<input class="quantity" id="ShowButton_value_1" type="text" name="quantity" value="1"/>
<a class="incr-btn_mobile" data-action="increase" data-target="cleanse_drop_1" href="#">+</a>
</div>
<label for='include' class="inlinelabel">Include Extra? ($5)</label>
<input type="checkbox" id="include" name='include' data-target="cleanse_drop_1" />
<div id="cleanse_drop_1" class="sum_output">= $7.99</div>
There you go my friend. I only change your js code. There is all the change I made:
Deleted your IncludePrice function since you could do it in only one row. And do never user function name for a variable. It could possibly break your code.
All switched for jQuery use instead of half jQuery and native JS.
Created a function for checkbox onclick to change the prince dynamicly.
I changed the names of your variables to make them more specific.
Added some comments to make the code clearer.
var _EXTRAVAL = 5;
$(".incr-btn_mobile").on("click", function(e) {
// Prevent default action
e.preventDefault();
// Set variable for the method
var button = $(this);
var labelNb = button.parent().find('.quantity');
var labelPrice = $("#" + button.attr('data-target'));
var currentNb = button.parent().find('.quantity').val();
var newNb = 0;
// Remove 'inactive' class
$('.incr-btn_mobile[data-action="decrease"]').removeClass('inactive');
// Increase or decrease
if (button.attr('data-action') == "increase") {
newNb = parseFloat(currentNb) + 1;
} else {
// Don't allow decrementing below 1
if (currentNb > 1) {
newNb = parseFloat(currentNb) - 1;
} else {
newNb = 1;
button.addClass('inactive');
}
}
var isExtra = $("#include").prop('checked') ? _EXTRAVAL : 0;
$(labelNb).val(newNb);
$(labelPrice).css('display', 'block').html("= $" + String((((newNb) * 7.99) + (isExtra)).toFixed(2)));
});
$("#include").on('click', function(){
// Set variable for method
var checkbox = $(this);
var labelPrice = $("#" + $(".incr-btn_mobile").attr('data-target'));
var labelPriceFloat = parseFloat(labelPrice.html().substring(4));
// If checkbox is check, increse price
if (checkbox.prop('checked')) {
labelPrice.html("= $" + String((labelPriceFloat + _EXTRAVAL).toFixed(2)));
} else {
labelPrice.html("= $" + String((labelPriceFloat - _EXTRAVAL).toFixed(2)));
}
});
.bg {
width: 100%;
}
.column {
float: left;
width: 50%;
padding: 10px;
}
/* Clear floats after the columns */
.row:after {
content: "";
display: table;
clear: both;
}
.count-input_mobile {
position: relative;
max-width: 1000%;
max-width: 400px;
margin-top: 10px;
text-align: center;
}
.count-input_mobile input {
width: 100%;
height: 42px;
border: 1px solid #000
border-radius: 2px;
background: none;
text-align: center;
}
.count-input_mobile input:focus {
outline: none;
}
.count-input_mobile .incr-btn_mobile {
display: block;
position: absolute;
width: 30px;
height: 30px;
font-size: 26px;
font-weight: 300;
text-align: center;
line-height: 30px;
top: 50%;
right: 0;
margin-top: -15px;
text-decoration:none;
}
.count-input_mobile .incr-btn_mobile:first-child {
right: auto;
left: 0;
top: 46%;
}
.count-input_mobile.count-input-sm {
max-width: 125px;
}
.count-input_mobile.count-input-sm input {
height: 36px;
}
.count-input_mobile.count-input-lg {
max-width: 200px;
}
.count-input_mobile.count-input-lg input {
height: 70px;
border-radius: 3px;
}
.button_mobile {
border: 1px solid #000;
border-radius: 2px;
background: none;
padding: 10.5px;
width:100%;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
cursor: pointer;
margin-top:10px;
}
.sum_output {
background: none;
padding: 9.5px;
width:100%;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
cursor: pointer;
margin-top:10px;
}
.accordion_img {
width:200%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<div class="count-input_mobile space-bottom">
<a class="incr-btn_mobile" data-action="decrease" data-target="cleanse_drop_1" href="#">–</a>
<input class="quantity" id="ShowButton_value_1" type="text" name="quantity" value="1"/>
<a class="incr-btn_mobile" data-action="increase" data-target="cleanse_drop_1" href="#">+</a>
</div>
<label for='include' class="inlinelabel">Include Extra? ($5)</label>
<input type="checkbox" id="include" name='include' data-target="cleanse_drop_1" />
<div id="cleanse_drop_1" class="sum_output">= $7.99</div>

Categories

Resources