calculate the sum of shopping cart - javascript

I want to calculate the total(sum) of all the purchases using the "+","-" to add and remove products from the shopping cart.It should display the amount on the left top corner in front of "total:".In front of each product, the total purchase of the single purchase is displayed.
Here a descriptive image
Here the html code:
<body>
<div class="shopping-cart">
<!-- Title -->
<div class="title">
Shopping Bag total :
</div>
<!-- Product #1 -->
<div class="item">
<div class="buttons">
<span class="delete-btn"></span>
<span class="like-btn"></span>
</div>
<div class="image">
<img src="item-1.png" alt="" />
</div>
<div class="description">
<span>Common Projects</span>
<span>Bball High</span>
<span>White</span>
</div>
<div class="quantity">
<button class="plus-btn" type="button" name="button"><img src="plus.svg" alt="" /></button>
<input type="text" value="0" class="input-btn" />
<button class="minus-btn" type="button" name="button"><img src="minus.svg" alt="" /></button>
</div>
<div class="total-price" id="549"><input type="number" value="0" class="result-btn" /></div>
</div>
<!-- Product #2 -->
<div class="item">
<div class="buttons">
<span class="delete-btn"></span>
<span class="like-btn"></span>
</div>
<div class="image">
<img src="item-2.png" alt=""/>
</div>
<div class="description">
<span>Maison Margiela</span>
<span>Future Sneakers</span>
<span>White</span>
</div>
<div class="quantity">
<button class="plus-btn" type="button" name="button"><img src="plus.svg" alt="" /></button>
<input type="text" value="0" class="input-btn" />
<button class="minus-btn" type="button" name="button"><img src="minus.svg" alt="" /></button>
</div>
<div class="total-price" id="270"><input type="number" value="0" class="result-btn" /></div>
</div>
<!-- Product #3 -->
<div class="item">
<div class="buttons">
<span class="delete-btn"></span>
<span class="like-btn"></span>
</div>
<div class="image">
<img src="item-3.png" alt="" />
</div>
<div class="description">
<span>Our Legacy</span>
<span>Brushed Scarf</span>
<span>Brown</span>
</div>
<div class="quantity">
<button class="plus-btn" type="button" name="button"><img src="plus.svg" alt="" /></button>
<input type="text" value="0" class="input-btn" />
<button class="minus-btn" type="button" name="button"><img src="minus.svg" alt="" /></button>
</div>
<div class="total-price" id="349"><input type="number" value="0" class="result-btn" /></div>
</div>
</div>
</body>
Here the JS code:
const items = document.querySelectorAll('.item');
items.forEach(function(item) {
const minusButton = item.querySelector('.minus-btn');
const plusButton = item.querySelector('.plus-btn');
const inputField = item.querySelector('.input-btn');
const resultField = item.querySelector('.result-btn');
minusButton.addEventListener('click', function minusProduct() {
const currentValue = Number(inputField.value);
if (currentValue > 0) {
inputField.value = currentValue - 1;
var x = item.querySelector('.total-price').id;
resultField = item.querySelector('.result-btn').value = x* inputField.value;
} else inputField.value = 0
});
plusButton.addEventListener('click', function plusProduct() {
const currentValue = Number(inputField.value);
if (currentValue < 100) {
inputField.value = currentValue + 1;
var x = item.querySelector('.total-price').id;
resultField = item.querySelector('.result-btn').value = x* inputField.value;
document.querySelector('.title').innerHTML = item.querySelector('.result-btn')[0].value
+item.querySelector('.result-btn')[1].value + item.querySelector('.result-btn')[2].value
} else inputField.value = 100
});
});

There are two thing that you need to do.
1. You need to convert value of total price and total price to number.
2. Set the innneHTML of dev other wise you will get the error. e.g. (
Uncaught TypeError: Assignment to constant variable.
at HTMLButtonElement.minusProduct)
So, in your JS
resultField.innerHTML = item.querySelector('.result-btn').value = Number(x) * Number(inputField.value);

Related

Dynamic input form not submitting

i have a dynamic form which lets you add and remove inputs. The issue is what even though it works visually, when submitting the form i wont get the values from inputs created by the JS function. If you need anything else let me know as this is about the last implementation to the website
Any ideas as to why? i leave my code below
The html:
<div class="form-container" id="form-container">
<div class="title-title">
<h3 class="recipe-pretitle">Recipe for</h3>
<form action="/recipes/create" enctype="multipart/form-data" method="POST">
<div>
<label for="title">
<input name="title" type="text" id="title" placeholder="Name of dish">
</label>
</div>
</div>
<div class="description-container">
<label class="description-label" for="description">A brief description of your dish: <br> (max 80char)</label>
<textarea name="description" type="text" id="description" cols="30" rows="5"></textarea>
</div>
<div class="directions-ingredients-container">
<div id="product-directions">
<div class="label-directions"><label for="directions">Cooking steps.</label></div>
<div class="controls-ol-container">
<div class="controls">
<i class="fa fa-sm">Add step</i>
<i class="fa fa-sm">Remove last step</i>
</div>
<div class="instruction-list-container">
<ol id="instruction-list">
</ol>
</div>
</div>
</div>
<div class="ingredients-container">
<div class="label-ingredients"><label for="Ingredients">Ingredients:</label></div>
<div class="controls-ol-container">
<div class="controls">
<i class="fa fa-sm">Add Ingredient</i>
<i class="fa fa-sm">Remove last Ingredient</i>
</div>
<div class="ingredient-list-container">
<ol id="ingredient-list">
</ol>
</div>
</div>
</div>
</div>
<div class="imageInputContainer">
<label id="image-label" for="image">Choose an image</label>
<input name="image" type="file" id="image">
</div>
<div>
<button type="submit">Upload</button>
</form>
</div>
</div>
Font end JS
var add_more_fields = document.getElementById("add_more_fields")
var remove_fields = document.getElementById("remove_fields")
var directions_container = document.getElementById('product-directions')
var instruction_list = document.getElementById('instruction-list')
add_more_fields.onclick = function () {
var node = document.createElement("li")
var newField = document.createElement('input')
newField.setAttribute('type', 'text')
newField.setAttribute('name', 'directions[]')
newField.setAttribute('placeholder', 'Add Instruction')
node.appendChild(newField)
instruction_list.appendChild(node)
}
remove_fields.onclick = function () {
var input_tags = instruction_list.getElementsByTagName('li')
if (input_tags.length > 1) {
instruction_list.removeChild(input_tags[(input_tags.length) - 1])
}
}
var add_more_fields_ingredients = document.getElementById("add_more_fields_ingredients")
var remove_fields_ingredients = document.getElementById("remove_fields_ingredients")
var ingredient_list = document.getElementById('ingredient-list')
add_more_fields_ingredients.onclick = function () {
var node = document.createElement("li")
var newField = document.createElement('input')
newField.setAttribute('type', 'text')
newField.setAttribute('name', 'Ingredients[]')
newField.setAttribute('placeholder', 'Add Ingredient')
node.appendChild(newField)
ingredient_list.appendChild(node)
}
remove_fields_ingredients.onclick = function () {
var input_tags = ingredient_list.getElementsByTagName('li')
if (input_tags.length > 1) {
ingredient_list.removeChild(input_tags[(input_tags.length) - 1])
}
}
your HTML is not valid, form element is not properly closed, move closing form tag outside button container, and form opening tag a level up
this should work, and now you probably need to modify styles and rearrange some elements, so you need to see to it that the form and HTML is valid, and adapt styles accordingly:
<div class="form-container" id="form-container">
<form action="/recipes/create" enctype="multipart/form-data" method="POST">
<div class="title-title">
<h3 class="recipe-pretitle">Recipe for</h3>
<div>
<label for="title">
<input name="title" type="text" id="title" placeholder="Name of dish">
</label>
</div>
</div>
<div class="description-container">
<label class="description-label" for="description">A brief description of your dish:
<br> (max 80char)</label>
<textarea name="description" type="text" id="description" cols="30" rows="5"></textarea>
</div>
<div class="directions-ingredients-container">
<div id="product-directions">
<div class="label-directions">
<label for="directions">Cooking steps.</label>
</div>
<div class="controls-ol-container">
<div class="controls">
<i class="fa fa-sm">Add step</i>
<i class="fa fa-sm">Remove last step</i>
</div>
<div class="instruction-list-container">
<ol id="instruction-list">
</ol>
</div>
</div>
</div>
<div class="ingredients-container">
<div class="label-ingredients">
<label for="Ingredients">Ingredients:</label>
</div>
<div class="controls-ol-container">
<div class="controls">
<i class="fa fa-sm">Add Ingredient</i>
<i class="fa fa-sm">Remove last Ingredient</i>
</div>
<div class="ingredient-list-container">
<ol id="ingredient-list">
</ol>
</div>
</div>
</div>
</div>
<div class="imageInputContainer">
<label id="image-label" for="image">Choose an image</label>
<input name="image" type="file" id="image">
</div>
<div>
<button type="submit">Upload</button>
</div>
</form>
</div>

How to handle multiple delete buttons JS

I'm having trouble handling multiple buttons to delete items on a cart page. I read about parentNode, operators delete, remove but none seem to work. Here's the code.
HTML:
<section id="cart__items">
<article class="cart__item" data-id="{product-ID}">
<div class="cart__item__img">
<img id ="image" alt="Photographie dun canapé">
</div>
<div class="cart__item__content">
<div class="cart__item__content__titlePrice">
<h2 class=title></h2>
<p class =price></p>
</div>
<div class="cart__item__content__settings">
<div class="cart__item__content__settings__quantity">
<p class= quantity>Qté : </p>
<input type="number" class="itemQuantity" name="itemQuantity" min="1" max="100" value="">
</div>
<div class="cart__item__content__settings__delete">
<p class="deleteItem">Supprimer</p>
</div>
</div>
</div>
</article>
JS:
let removeCart = Array.prototype.slice.call(document.getElementsByTagName('article'), 0);
for (let i = 0; i < removeCart.length; i++) {
let removeItems = (removeCart[i]);
console.log(removeItems)
let removeButton = document.getElementsByClassName('deleteItem');
for (let i = 0; i < removeButton.length; i++) {
removeButton[i].addEventListener("click", function (event) {
removeItems.remove(removeCart[i])
})
}
So as you can see, this allows me to delete entirety of the cart content. How could I set each buton to delete the article (and its localStorage) inside which they exist? If any of you could help that'd be great.
Snippet below makes use of event delegation
If you were to dynamically create all the cart items, manually attaching event listeners wouldn't be possible.
In order to handle LocalStorage update (not quite sure of its structure since you haven't provided anything) I assume you're utilizing some sort of product-id or data-id, so just filter out the id and set localstorage again.
// pass the id of item to be deleted
const updateCartLocalStorage = (cartItemId) => {
const currentCartLS = JSON.parse(localStorage.getItem('cart'));
const updatedCartLS = currentCartLS.filter(c => c.id !==
cartItemId);
localStorage.setItem('cart', JSON.stringify(updatedCartLS));
}
const cartItemsSection = document.querySelector('#cart__items');
const handleDeleteItem = (e) => {
// if user clicks on delete item, find and remove the parent article
if (e.target.classList.contains('deleteItem')) {
const parentArticle =
e.target.parentElement.parentElement.parentElement.parentElement;
console.log(parentArticle.dataset.id);
parentArticle.remove();
updateLocalCartLocalStorage(<id>);
} else {
return;
}
};
cartItemsSection.addEventListener('click', handleDeleteItem);
// alternative solution (to get rid of stacking .parentElement...)
const cartArticles = document.querySelectorAll('.cart__item');
const deleteCartItem = (e) => {
if (e.target.classList.contains('deleteItem')) {
const parent = e.currentTarget;
parent.remove();
updateLocalCartLocalStorage(<id>);
} else {
return;
}
};
cartArticles.forEach((article) => {
article.addEventListener('click', deleteCartItem);
});
<section id="cart__items">
<article class="cart__item" data-id="1" style="background-color: blue">
<div class="cart__item__img">
<img id="image" alt="Photographie dun canapé" />
</div>
<div class="cart__item__content">
<div class="cart__item__content__titlePrice">
<h2 class="title"></h2>
<p class="price"></p>
</div>
<div class="cart__item__content__settings">
<div class="cart__item__content__settings__quantity">
<p class="quantity">Qté :</p>
<input
type="number"
class="itemQuantity"
name="itemQuantity"
min="1"
max="100"
value=""
/>
</div>
<div class="cart__item__content__settings__delete">
<button class="deleteItem">Supprimer</button>
</div>
</div>
</div>
</article>
<article class="cart__item" data-id="2" style="background-color: red">
<div class="cart__item__img">
<img id="image" alt="Photographie dun canapé" />
</div>
<div class="cart__item__content">
<div class="cart__item__content__titlePrice">
<h2 class="title"></h2>
<p class="price"></p>
</div>
<div class="cart__item__content__settings">
<div class="cart__item__content__settings__quantity">
<p class="quantity">Qté :</p>
<input
type="number"
class="itemQuantity"
name="itemQuantity"
min="1"
max="100"
value=""
/>
</div>
<div class="cart__item__content__settings__delete">
<button class="deleteItem">Supprimer</button>
</div>
</div>
</div>
</article>
<article class="cart__item" data-id="3" style="background-color: green">
<div class="cart__item__img">
<img id="image" alt="Photographie dun canapé" />
</div>
<div class="cart__item__content">
<div class="cart__item__content__titlePrice">
<h2 class="title"></h2>
<p class="price"></p>
</div>
<div class="cart__item__content__settings">
<div class="cart__item__content__settings__quantity">
<p class="quantity">Qté :</p>
<input
type="number"
class="itemQuantity"
name="itemQuantity"
min="1"
max="100"
value=""
/>
</div>
<div class="cart__item__content__settings__delete">
<button class="deleteItem">Supprimer</button>
</div>
</div>
</div>
</article>
<article class="cart__item" data-id="4" style="background-color: yellow">
<div class="cart__item__img">
<img id="image" alt="Photographie dun canapé" />
</div>
<div class="cart__item__content">
<div class="cart__item__content__titlePrice">
<h2 class="title"></h2>
<p class="price"></p>
</div>
<div class="cart__item__content__settings">
<div class="cart__item__content__settings__quantity">
<p class="quantity">Qté :</p>
<input
type="number"
class="itemQuantity"
name="itemQuantity"
min="1"
max="100"
value=""
/>
</div>
<div class="cart__item__content__settings__delete">
<button class="deleteItem">Supprimer</button>
</div>
</div>
</div>
</article>
</section>

Javascript document.ready repeat in loop (Without DRY)

I have an HTML code that contains 3 groups of radio buttons. each group has an active class in its images section. (In fact Active-1, Active-2 and Active-2 in the Image tag)
<!-------- Select Color ---------->
<div class="color-0">
<!--- Checked --->
<div>
<input type="radio" data-image="navy-blue-0" id="navy-blue-0" name="color-0" value="navy-blue-0" checked>
<label for="navy-blue-0"><span></span></label>
</div>
<div>
<input type="radio" data-image="aqua-0" id="aqua-0" name="color-0" value="aqua-0">
<label for="aqua-0"><span></span></label>
</div>
<div>
<input type="radio" data-image="pink-0" id="pink-0" name="color-0" value="pink-0">
<label for="pink-0"><span></span></label>
</div>
</div>
<div class="color-1">
<!--- Checked --->
<div>
<input type="radio" data-image="navy-blue-1" id="navy-blue-1" name="color" value="navy-blue-1" checked>
<label for="navy-blue-1"><span></span></label>
</div>
<div>
<input type="radio" data-image="aqua-1" id="aqua-1" name="color-1" value="aqua-1">
<label for="aqua-1"><span></span></label>
</div>
<div>
<input type="radio" data-image="pink-1" id="pink-1" name="color-1" value="aqua-1">
<label for="pink-1"><span></span></label>
</div>
</div>
<div class="color-2">
<!--- Checked --->
<div>
<input type="radio" data-image="navy-blue-2" id="navy-blue-2" name="color-2" value="navy-blue-2" checked>
<label for="navy-blue-2"><span></span></label>
</div>
<div>
<input type="radio" data-image="aqua-2" id="aqua-2" name="color-2" value="aqua-2">
<label for="aqua-2"><span></span></label>
</div>
<div>
<input type="radio" data-image="pink-2" id="pink-2" name="color-2" value="aqua-2">
<label for="pink-2"><span></span></label>
</div>
</div>
<!-------- Show Image ---------->
<div class="img-0">
<!--- Active-0 --->
<img class="img-fluid active-0" data-image="navy-blue-0" src="img/img-navy-blue-0.png" alt="">
<img class="img-fluid" data-image="aqua-0" src="img/img-aqua-0.png" alt="">
<img class="img-fluid" data-image="pink-0" src="img/img-pink-0.png" alt="">
<img class="img-fluid" data-image="red-0" src="img/img-red-0.png" alt="">
<img class="img-fluid" data-image="white-0" src="img/img-white-0.png" alt="">
</div>
<div class="img-1">
<!--- Active-1 --->
<img class="img-fluid active-1" data-image="navy-blue-1" src="img/img-navy-blue-1.png" alt="">
<img class="img-fluid" data-image="aqua-1" src="img/img-aqua-1.png" alt="">
<img class="img-fluid" data-image="pink-1" src="img/img-pink-1.png" alt="">
<img class="img-fluid" data-image="red-1" src="img/img-red-1.png" alt="">
<img class="img-fluid" data-image="white-1" src="img/img-white-1.png" alt="">
</div>
<div class="img-2">
<!--- Active-2 --->
<img class="img-fluid active-2" data-image="navy-blue-2" src="img/img-navy-blue-2.png" alt="">
<img class="img-fluid" data-image="aqua-2" src="img/img-aqua-2.png" alt="">
<img class="img-fluid" data-image="pink-2" src="img/img-pink-2.png" alt="">
<img class="img-fluid" data-image="red-2" src="img/img-red-2.png" alt="">
<img class="img-fluid" data-image="white-2" src="img/img-white-2.png" alt="">
</div>
The problem now is that I had to write code three times in the JavaScript:
$(document).ready(function () {
$('.color-0 input').on('click', function () {
var x = $(this).attr('data-image');
$('.active-0').removeClass('active-0');
$('.img-0 img[data-image = ' + x + ']').addClass('active-0');
$(this).addClass('active-0');
});
});
$(document).ready(function () {
$('.color-1 input').on('click', function () {
var x = $(this).attr('data-image');
$('.active-1').removeClass('active-1');
$('.img-1 img[data-image = ' + x + ']').addClass('active-1');
$(this).addClass('active-1');
});
});
$(document).ready(function () {
$('.color-2 input').on('click', function () {
var x = $(this).attr('data-image');
$('.active-2').removeClass('active-2');
$('.img-2 img[data-image = ' + x + ']').addClass('active-2');
$(this).addClass('active-2');
});
});
So I tried using loops but the code didn't work. like this:
var shoePart = [0, 1, 2, 3];
for (var i = 0; i < shoePart.length; i++) {
$(document).ready(function () {
$('.color-' + shoePart[i] + ' input').on('click', function () {
var x = $(this).attr('data-image');
$('.active-' + shoePart[i]).removeClass('active-' + shoePart[i]);
$('.img-' + shoePart[i] + ' img[data-image = ' + x + ']').addClass('active-' + shoePart[i]);
$(this).addClass('active-' + shoePart[i]);
});
});
}
You can add a common class on all three tags and an attribute of number. Then can call your jQuery on that as below:
<!-------- Select Color ---------->
<div class="color-0 common-color" attr-number="0">
<!--- Checked --->
<div>
<input type="radio" data-image="navy-blue-0" id="navy-blue-0" name="color-0" value="navy-blue-0" checked>
<label for="navy-blue-0"><span></span></label>
</div>
<div>
<input type="radio" data-image="aqua-0" id="aqua-0" name="color-0" value="aqua-0">
<label for="aqua-0"><span></span></label>
</div>
<div>
<input type="radio" data-image="pink-0" id="pink-0" name="color-0" value="pink-0">
<label for="pink-0"><span></span></label>
</div>
</div>
<div class="color-1 common-color" attr-number="1">
<!--- Checked --->
<div>
<input type="radio" data-image="navy-blue-1" id="navy-blue-1" name="color" value="navy-blue-1" checked>
<label for="navy-blue-1"><span></span></label>
</div>
<div>
<input type="radio" data-image="aqua-1" id="aqua-1" name="color-1" value="aqua-1">
<label for="aqua-1"><span></span></label>
</div>
<div>
<input type="radio" data-image="pink-1" id="pink-1" name="color-1" value="aqua-1">
<label for="pink-1"><span></span></label>
</div>
</div>
<div class="color-2 common-color" attr-number="2">
<!--- Checked --->
<div>
<input type="radio" data-image="navy-blue-2" id="navy-blue-2" name="color-2" value="navy-blue-2" checked>
<label for="navy-blue-2"><span></span></label>
</div>
<div>
<input type="radio" data-image="aqua-2" id="aqua-2" name="color-2" value="aqua-2">
<label for="aqua-2"><span></span></label>
</div>
<div>
<input type="radio" data-image="pink-2" id="pink-2" name="color-2" value="aqua-2">
<label for="pink-2"><span></span></label>
</div>
</div>
and then can call jQuery as below:
$(document).ready(function () {
$('.common-color input').on('click', function () {
var x = $(this).attr('data-image');
var elemCounter = $(this).closest(".common-color").attr("attr-number");
$('.active-'+elemCounter).removeClass('active-'+elemCounter);
$('.img-'+ elemCounter +' img[data-image = ' + x + ']').addClass('active-'+elemCounter);
$(this).addClass('active-'+elemCounter);
});
});
Hope it helps you!!

Calculating the total of my purchase items

i want to calculate the total of my purchase items by adding the sum of the purchases for each item(For exp: 2 shoes * price unit + 1 tshit * price unit) in front of "Shopping Bag total :"
here a description image :
i already written a fonctionnal code that add/ remove products and also calculate the total purchase for each item. The last part of the code which is calculating the sum of my total purchase is not working.I'm confused and i don't know how to solve it.
Here the html5 code:
<div class="shopping-cart">
<!-- Title -->
<div class="title">
Shopping Bag total : <input type="number" value="0" class="total-result-input" />
</div>
<!-- Product #1 -->
<div class="item">
<div class="buttons">
<span class="delete-btn"></span>
<span class="like-btn"></span>
</div>
<div class="image">
<img src="item-1.png" alt="" />
</div>
<div class="description">
<span>Common Projects</span>
<span>Bball High</span>
<span>White</span>
</div>
<div class="quantity">
<button class="plus-btn" type="button" name="button""><img src="plus.svg" alt="" /></button>
<input type="text" value="0" class="input-btn" />
<button class="minus-btn" type="button" name="button"><img src="minus.svg" alt="" /></button>
</div>
<div class="total-price" id="549"><input type="number" value="0" class="result-btn" /></div>
</div>
<!-- Product #2 -->
<div class="item">
<div class="buttons">
<span class="delete-btn"></span>
<span class="like-btn"></span>
</div>
<div class="image">
<img src="item-2.png" alt=""/>
</div>
<div class="description">
<span>Maison Margiela</span>
<span>Future Sneakers</span>
<span>White</span>
</div>
<div class="quantity">
<button class="plus-btn" type="button" name="button"><img src="plus.svg" alt="" /></button>
<input type="text" value="0" class="input-btn" />
<button class="minus-btn" type="button" name="button"><img src="minus.svg" alt="" /></button>
</div>
<div class="total-price" id="270"><input type="number" value="0" class="result-btn" /></div>
</div>
<!-- Product #3 -->
<div class="item">
<div class="buttons">
<span class="delete-btn"></span>
<span class="like-btn"></span>
</div>
<div class="image">
<img src="item-3.png" alt="" />
</div>
<div class="description">
<span>Our Legacy</span>
<span>Brushed Scarf</span>
<span>Brown</span>
</div>
<div class="quantity">
<button class="plus-btn" type="button" name="button" ><img src="plus.svg" alt="" /></button>
<input type="text" value="0" class="input-btn" />
<button class="minus-btn" type="button" name="button"><img src="minus.svg" alt="" /></button>
</div>
<div class="total-price" id="349"><input type="number" value="0" class="result-btn" /></div>
</div>
</div>
Here the JS code:
var items = document.querySelectorAll('.item');
items.forEach(function(item) {
var minusButton = item.querySelector('.minus-btn');
var plusButton = item.querySelector('.plus-btn');
var inputField = item.querySelector('.input-btn');
var resultField = item.querySelector('.result-btn');
minusButton.addEventListener('click', function minusProduct() {
var currentValue = Number(inputField.value);
if (currentValue > 0) {
inputField.value = currentValue - 1;
var x = item.querySelector('.total-price').id;
resultField = item.querySelector('.result-btn').value = x* inputField.value;
} else inputField.value = 0
});
plusButton.addEventListener('click', function plusProduct() {
var currentValue = Number(inputField.value);
if (currentValue < 100) {
inputField.value = currentValue + 1;
var x = item.querySelector('.total-price').id;
resultField = item.querySelector('.result-btn').value = Number(x)* Number(inputField.value);
} else inputField.value = 100
});
});
const results = document.querySelectorAll('.result-btn');
let total = 0;
results.forEach((result) => {
total += result.value
});
document.querySelector('.total-result-input').value = total;
i just add
document.querySelector('.total-result-input').value = [].slice.call(document.querySelectorAll(".total-price > input")).reduce((acc, el) => acc + parseInt(el.value), 0)
inside of your click event and all will work good
var items = document.querySelectorAll('.item');
items.forEach(function(item) {
var minusButton = item.querySelector('.minus-btn');
var plusButton = item.querySelector('.plus-btn');
var inputField = item.querySelector('.input-btn');
var resultField = item.querySelector('.result-btn');
minusButton.addEventListener('click', function minusProduct() {
var currentValue = Number(inputField.value);
if (currentValue > 0) {
inputField.value = currentValue - 1;
var x = item.querySelector('.total-price').id;
resultField = item.querySelector('.result-btn').value = x * inputField.value;
document.querySelector('.total-result-input').value = [].slice.call(document.querySelectorAll(".total-price > input")).reduce((acc, el) => acc + parseInt(el.value), 0)
} else inputField.value = 0
});
plusButton.addEventListener('click', function plusProduct() {
var currentValue = Number(inputField.value);
if (currentValue < 100) {
inputField.value = currentValue + 1;
var x = item.querySelector('.total-price').id;
resultField = item.querySelector('.result-btn').value = Number(x) * Number(inputField.value);
document.querySelector('.total-result-input').value = [].slice.call(document.querySelectorAll(".total-price > input")).reduce((acc, el) => acc + parseInt(el.value), 0)
} else inputField.value = 100
});
});
const results = document.querySelectorAll('.result-btn');
let total = 0;
results.forEach((result) => {
total += result.value
});
document.querySelector('.total-result-input').value = total;
<div class="shopping-cart">
<!-- Title -->
<div class="title">
Shopping Bag total : <input type="number" value="0" class="total-result-input" />
</div>
<!-- Product #1 -->
<div class="item">
<div class="buttons">
<span class="delete-btn"></span>
<span class="like-btn"></span>
</div>
<div class="image">
<img src="item-1.png" alt="" />
</div>
<div class="description">
<span>Common Projects</span>
<span>Bball High</span>
<span>White</span>
</div>
<div class="quantity">
<button class="plus-btn" type="button" name="button"">+</button>
<input type=" text" value="0" class="input-btn" />
<button class="minus-btn" type="button" name="button">-</button>
</div>
<div class="total-price" id="549"><input type="number" value="0" class="result-btn" /></div>
</div>
<!-- Product #2 -->
<div class="item">
<div class="buttons">
<span class="delete-btn"></span>
<span class="like-btn"></span>
</div>
<div class="image">
<img src="item-2.png" alt=""/>
</div>
<div class="description">
<span>Maison Margiela</span>
<span>Future Sneakers</span>
<span>White</span>
</div>
<div class="quantity">
<button class="plus-btn" type="button" name="button">+</button>
<input type="text" value="0" class="input-btn" />
<button class="minus-btn" type="button" name="button">-</button>
</div>
<div class="total-price" id="270"><input type="number" value="0" class="result-btn" /></div>
</div>
<!-- Product #3 -->
<div class="item">
<div class="buttons">
<span class="delete-btn"></span>
<span class="like-btn"></span>
</div>
<div class="image">
<img src="item-3.png" alt="" />
</div>
<div class="description">
<span>Our Legacy</span>
<span>Brushed Scarf</span>
<span>Brown</span>
</div>
<div class="quantity">
<button class="plus-btn" type="button" name="button">+</button>
<input type="text" value="0" class="input-btn" />
<button class="minus-btn" type="button" name="button">-</button>
</div>
<div class="total-price" id="349"><input type="number" value="0" class="result-btn" /></div>
</div>
</div>
const results = document.querySelectorAll('.result-btn');
let total = 0;
results.forEach((result) => {
total += result.value
});
document.querySelector('.total-result-input').value = total;
Put it in a reasonable function and call this function on every change (plus, minus).

Hiding a div if a value is under 1

I want the application to behave this way so that when I click on "Show Order" if any of the values are 0 or blank, I don't want div id item * x be shown:
var divs = document.getElementsByTagName('div');
var toggle = function() {
for (var i = 0, l = divs.length; i < l; i++) {
if (divs[i].getAttribute('class') == 'problem')
if (divs[i].style.display == 'none') divs[i].style.display = '';
else divs[i].style.display = 'none';
var x = document.getElementById("mySelect").value;
var y = document.getElementById("item1").value;
if (x < 1) {
y.style.display === "none"
} else {
document.getElementById("demo").innerHTML = x;
}
var x = document.getElementById("mySelect1").value;
document.getElementById("demo1").innerHTML = x;
var x = document.getElementById("mySelect2").value;
document.getElementById("demo2").innerHTML = x;
}
}
document.getElementById('Toggle').onclick = toggle;
<div class="problem">
<div class="row">
<div class="col-3">
<form>
<input type="number" id="mySelect" name="mySelect" autocomplete="off" style="width: 3em;"> Sausage
<br>
</form>
</div>
<div class="col-3">
<form>
<input type="number" id="mySelect1" name="mySelect1" autocomplete="off" style="width: 3em;"> Pancake
<br>
</form>
</div>
<div class="col-2">
<form>
<input type="number" id="mySelect2" name="mySelect2" autocomplete="off" style="width: 3em;"> Milk
</form>
</div>
<div class="col-4">
</div>
</div>
<div class="row">
<div class="col-12">
<p>
<button type="button" class="button" id="Toggle" onclick="myFunction()">Show Order</button>
</p>
</div>
</div>
</div>
<div class="row">
<div class="col-12">
<div style="display:none;" class="problem">Please show this to the cashier.</div>
<div style="display:none;" class="problem">
<h2>Hello, they ordered:</h2>
</div>
<div id="item1" style="display:none;" class="problem">
<h2><span style="font-size: xx-large; color: green;" id="demo"></span>x Sausage(s)</h2>
</div>
<div id="item2" style="display:none;" class="problem">
<h2><span style="font-size: xx-large; color: green;" id="demo1"></span>x Pancake(s)</h2>
</div>
<div id="item3" style="display:none;" class="problem">
<h2><span style="font-size: xx-large; color: green;" id="demo2"></span>x Cup of Milk(s)</h2>
</div>
<div style="display:none;" class="problem">
<h2>Thank you</h2>
</div>
<div style="display:none;" class="problem">Please refresh your browser to restart your order</div>
</div>
</div>
I have added my full code from JSFiddle here.
Check this simpler approach
Give a display class to div to be div to be toggled
Check for any input values to be >= 1
Demo
var toggle = function() {
var x1 = Number(document.getElementById("mySelect").value);
var x2 = Number(document.getElementById("mySelect1").value);
var x3 = Number(document.getElementById("mySelect2").value);
document.querySelectorAll(".display .problem").forEach(function(el) {
el.style.display = x1 >= 1 || x2 >= 1 || x3 >= 1 ? "block" : "none";
});
document.getElementById("demo").innerHTML = (x1 || 0);
document.getElementById("demo1").innerHTML = (x2 || 0);
document.getElementById("demo2").innerHTML = (x3 || 0);
}
document.getElementById('Toggle').onclick = toggle;
<div class="problem">
<div class="row">
<div class="col-3">
<form>
<input type="number" id="mySelect" name="mySelect" autocomplete="off" style="width: 3em;"> Sausage
<br>
</form>
</div>
<div class="col-3">
<form>
<input type="number" id="mySelect1" name="mySelect1" autocomplete="off" style="width: 3em;"> Pancake
<br>
</form>
</div>
<div class="col-2">
<form>
<input type="number" id="mySelect2" name="mySelect2" autocomplete="off" style="width: 3em;"> Milk
</form>
</div>
<div class="col-4">
</div>
</div>
<div class="row">
<div class="col-12">
<p>
<button type="button" class="button" id="Toggle" onclick="myFunction()">Show Order</button>
</p>
</div>
</div>
</div>
<div class="row display">
<div class="col-12">
<div style="display:none;" class="problem">Please show this to the cashier.</div>
<div style="display:none;" class="problem">
<h2>Hello, they ordered:</h2>
</div>
<div id="item1" style="display:none;" class="problem">
<h2><span style="font-size: xx-large; color: green;" id="demo"></span>x Sausage(s)</h2>
</div>
<div id="item2" style="display:none;" class="problem">
<h2><span style="font-size: xx-large; color: green;" id="demo1"></span>x Pancake(s)</h2>
</div>
<div id="item3" style="display:none;" class="problem">
<h2><span style="font-size: xx-large; color: green;" id="demo2"></span>x Cup of Milk(s)</h2>
</div>
<div style="display:none;" class="problem">
<h2>Thank you</h2>
</div>
<div style="display:none;" class="problem">Please refresh your browser to restart your order</div>
</div>
</div>
You can loop through all the divs with class="problem" and check their input's values. If there's nothing, then don't show it. If it isn't empty, show it.
You can achieve this with var allDivs = querySelectorAll('.problem input'); to get the inputs in the divs (since we know they have class="problem"), and then loop through that and use an if to check allDivs[i].value.
I didn't want to give the code directly, so hopefully this helps answer your question!
Here you are :
`https://jsfiddle.net/1znqk6us/1/`
I've removed onlick event on button because you don't use this, and for loop.

Categories