Why is the '.value' property not working? - javascript

function updateCartTotal() {
var cartItemContainer = document.getElementsByClassName('center-cart-items')[0]
var cartRows = cartItemContainer.getElementsByClassName('cart-row')
for (var i = 0; i < cartRows.length; i++) {
var cartRow = cartRows[i]
var priceElement = cartRow.getElementsByClassName('cart-price')[0]
var quantityElement = cartRow.getElementsByClassName('cart-quantity-input')[0]
var price = parseFloat(priceElement.innerText.replace('$', ''))
var quantity = quantityElement.value
console.log(price * quantity)
}
}
<div class="center-cart-items">
<div class="cart-row">
<div class="cart-item cart-column">
<img class="cart-item-image" src="#" width="100" height="100" />
<span class="cart-item-title"> T-shirt</span>
</div>
<span class="cart-price cart-column"> $29.99</span>
<div class="cart-quantity cart-column">
<input class="cart-quantity-input" type="number" value="2" />
<button class="btn-remove" role="button">REMOVE</button>
</div>
</div>
When I run the code, I get a source error that says
Cannot read properties of undefined (reading 'value')
Not sure what is going on here, I am new to all of this and following guides to help me build.

The bug occurs before the reference to cartRows. There is no .center-cart-items class in the snippet you gave, and if you delete the reference to it, your code works fine (see snippet).
Check your complete html source, the js reference to assign cartItemContainer is probably the problem.
function updateCartTotal() {
//var cartItemContainer = document.getElementsByClassName('center-cart-items')[0]
var cartRows = document.getElementsByClassName('cart-row')
for (var i = 0; i < cartRows.length; i++) {
var cartRow = cartRows[i]
var priceElement = cartRow.getElementsByClassName('cart-price')[0]
var quantityElement = cartRow.getElementsByClassName('cart-quantity-input')[0]
var price = parseFloat(priceElement.innerText.replace('$', ''))
var quantity = quantityElement.value
console.log(price * quantity)
}
return (price * quantity);
}
console.log(updateCartTotal());
<div class="cart-row">
<div class="cart-item cart-column">
<img class="cart-item-image" src="#" width="100" height="100" />
<span class="cart-item-title"> T-shirt</span>
</div>
<span class="cart-price cart-column"> $29.99</span>
<div class="cart-quantity cart-column">
<input class="cart-quantity-input" type="number" value="2" />
<button class="btn-remove" role="button">REMOVE</button>
</div>
</div>

I have recreated your code in codePen and it works fine:
https://codepen.io/SweetChillyPhilly/pen/xxpjyNQ
<div class="center-cart-items">
<div class="cart-row">
<div class="cart-item cart-column">
<img class="cart-item-image" src="#" width="100" height="100" />
<span class="cart-item-title"> T-shirt</span>
</div>
<span class="cart-price cart-column"> $29.99</span>
<div class="cart-quantity cart-column">
<input class="cart-quantity-input" type="number" value="2" />
<button class="btn-remove" role="button">REMOVE</button>
</div>
</div>
<div class="cart-row">
<div class="cart-item cart-column">
<img class="cart-item-image" src="#" width="100" height="100" />
<span class="cart-item-title"> T-shirt</span>
</div>
<span class="cart-price cart-column"> $29.99</span>
<div class="cart-quantity cart-column">
<input class="cart-quantity-input" type="number" value="2" />
<button class="btn-remove" role="button">REMOVE</button>
</div>
</div>
<div class="cart-row">
<div class="cart-item cart-column">
<img class="cart-item-image" src="#" width="100" height="100" />
<span class="cart-item-title"> T-shirt</span>
</div>
<span class="cart-price cart-column"> $29.99</span>
<div class="cart-quantity cart-column">
<input class="cart-quantity-input" type="number" value="2" />
<button class="btn-remove" role="button">REMOVE</button>
</div>
</div>
</div>
JS:
function updateCartTotal() {
var cartItemContainer = document.getElementsByClassName('center-cart-items')[0]
var cartRows = cartItemContainer.getElementsByClassName('cart-row')
for (var i = 0; i < cartRows.length; i++) {
var cartRow = cartRows[i]
var priceElement = cartRow.getElementsByClassName('cart-price')[0]
var quantityElement = cartRow.getElementsByClassName('cart-quantity-input')[0]
var price = parseFloat(priceElement.innerText.replace('$', ''))
var quantity = quantityElement.value
console.log(price * quantity)
}
}
updateCartTotal();
Your console log is working as expected.
So i suspect your issue lies outside of this code.

Related

My Javascript code does not work on first click

my JavaScript code for removing items from cart does not work on first click . what should I do ? where is the problem ?!
*EDITED : Thank you for the first answer . I just uploaded my HTML for you to have a look . My mother container is actually "main-cart-content-container" .
function removeCartItem() {
for (i = 0; i < document.getElementsByClassName('main-cart-content-container').length; i++) {
let button = document.getElementsByClassName('fa-trash')[i];
let qty1 = document.getElementsByClassName('cart-qty')[i];
let rmv = document.getElementsByClassName('main-cart-content-container')[i];
button.onclick = function() {
if (qty1.value < 2) {
rmv.remove();
cartNum = cartNum - 1;
document.getElementById('counter-eclipse-num').innerText = cartNum;
} else {
qty1.value = qty1.value - 1;
cartNum = cartNum - 1;
document.getElementById('counter-eclipse-num').innerText = cartNum;
}
}
}
}
<div class="polygon-cart">
<i class="fas fa-shopping-cart" id="cart-icon"></i>
<div class="counter-eclipse">
<p class="counter-eclipse-num" id="counter-eclipse-num">4 </p>
</div>
<div class="main-cart-content-container" id="main-cart-content-container">
<div class="cart-content-container">
<span class="cart-price" dir="rtl">159 هزارتومان</span>
<div class="cart-qty-container">
<input dir="rtl" type="number" min="1" value="1" class='cart-qty' id="cart-qty" oninput="this.value =
!!this.value && Math.abs(this.value) >= 0 ? Math.abs(this.value) : null">
<label for="cart-qty" class="cart-qty-label" dir="rtl">تعداد &nbsp : &nbsp</label>
</div>
اکانت بازی Battlefield V Deluxe Edition
<i class="fas fa-trash" id="trash-icon" onclick="removeCartItem()"></i>
<div class="cart-product-img-container">
<img src="/img/BFV.jpg" class="cart-product-img">
</div>
</div>
</div>
<div class="main-cart-content-container" id="main-cart-content-container">
<div class="cart-content-container">
<span class="cart-price" dir="rtl">559 هزارتومان</span>
<div class="cart-qty-container">
<input dir="rtl" type="number" min="1" value="3" class='cart-qty' id="cart-qty" oninput="this.value =
!!this.value && Math.abs(this.value) >= 0 ? Math.abs(this.value) : null">
<label for="cart-qty" class="cart-qty-label" dir="rtl">تعداد &nbsp : &nbsp</label>
</div>
اکانت بازی Battlefield V Deluxe Edition
<i class="fas fa-trash" id="trash-icon" onclick="removeCartItem()"></i>
<div class="cart-product-img-container">
<img src="/img/BFV.jpg" class="cart-product-img">
</div>
</div>
</div>
<div class="cart-info-top">
<button class="cart-checkout-btn">تسویه نهایی</button>
<span class="cart-whole-price">جمع مبلغ سبد خرید شما : 200 هزارتومان</span>
</div>
I suggest you delegate
Native (vanilla) JS
document.querySelector(".polygon-cart").addEventListener("click", function(e) {
const tgt = e.target; // we may need a .closest("button") here
if (tgt.classList.contains("fa-trash")) {
const container = tgt.closest(".main-cart-content-container");
const qty = container.querySelector(".cart-qty").value
if (qty < 2) {
container.remove()
console.log("removed since qty < 2:",qty)
}
}
})
<div class="polygon-cart">
<i class="fas fa-shopping-cart" id="cart-icon"></i>
<div class="counter-eclipse">
<p class="counter-eclipse-num" id="counter-eclipse-num">4 </p>
</div>
<div class="main-cart-content-container">
<div class="cart-content-container">
<span class="cart-price" dir="rtl">159 هزارتومان</span>
<div class="cart-qty-container">
<input dir="rtl" type="number" min="1" value="1" class='cart-qty' id="cart-qty" oninput="this.value =
!!this.value && Math.abs(this.value) >= 0 ? Math.abs(this.value) : null">
<label for="cart-qty" class="cart-qty-label" dir="rtl">تعداد &nbsp : &nbsp</label>
</div>
اکانت بازی Battlefield V Deluxe Edition
<i class="fas fa-trash" id="trash-icon">TRASH</i>
<div class="cart-product-img-container">
<img src="/img/BFV.jpg" class="cart-product-img">
</div>
</div>
</div>
<div class="main-cart-content-container">
<div class="cart-content-container">
<span class="cart-price" dir="rtl">559 هزارتومان</span>
<div class="cart-qty-container">
<input dir="rtl" type="number" min="1" value="3" class='cart-qty' id="cart-qty" oninput="this.value =
!!this.value && Math.abs(this.value) >= 0 ? Math.abs(this.value) : null">
<label for="cart-qty" class="cart-qty-label" dir="rtl">تعداد &nbsp : &nbsp</label>
</div>
اکانت بازی Battlefield V Deluxe Edition
<i class="fas fa-trash" id="trash-icon">TRASH</i>
<div class="cart-product-img-container">
<img src="/img/BFV.jpg" class="cart-product-img">
</div>
</div>
</div>
<div class="cart-info-top">
<button class="cart-checkout-btn">تسویه نهایی</button>
<span class="cart-whole-price">جمع مبلغ سبد خرید شما : 200 هزارتومان</span>
</div>
jQuery
$(".polygon-cart").on("click", ".fa-trash", function(e) {
const $container = $(this).closest(".main-cart-content-container");
const qty = $container.find(".cart-qty").val();
if (qty < 2) $container.remove()
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="polygon-cart">
<i class="fas fa-shopping-cart" id="cart-icon"></i>
<div class="counter-eclipse">
<p class="counter-eclipse-num" id="counter-eclipse-num">4 </p>
</div>
<div class="main-cart-content-container">
<div class="cart-content-container">
<span class="cart-price" dir="rtl">159 هزارتومان</span>
<div class="cart-qty-container">
<input dir="rtl" type="number" min="1" value="1" class='cart-qty' id="cart-qty" oninput="this.value =
!!this.value && Math.abs(this.value) >= 0 ? Math.abs(this.value) : null">
<label for="cart-qty" class="cart-qty-label" dir="rtl">تعداد &nbsp : &nbsp</label>
</div>
اکانت بازی Battlefield V Deluxe Edition
<i class="fas fa-trash" id="trash-icon">TRASH</i>
<div class="cart-product-img-container">
<img src="/img/BFV.jpg" class="cart-product-img">
</div>
</div>
</div>
<div class="main-cart-content-container">
<div class="cart-content-container">
<span class="cart-price" dir="rtl">559 هزارتومان</span>
<div class="cart-qty-container">
<input dir="rtl" type="number" min="1" value="3" class='cart-qty' id="cart-qty" oninput="this.value =
!!this.value && Math.abs(this.value) >= 0 ? Math.abs(this.value) : null">
<label for="cart-qty" class="cart-qty-label" dir="rtl">تعداد &nbsp : &nbsp</label>
</div>
اکانت بازی Battlefield V Deluxe Edition
<i class="fas fa-trash" id="trash-icon">TRASH</i>
<div class="cart-product-img-container">
<img src="/img/BFV.jpg" class="cart-product-img">
</div>
</div>
</div>
<div class="cart-info-top">
<button class="cart-checkout-btn">تسویه نهایی</button>
<span class="cart-whole-price">جمع مبلغ سبد خرید شما : 200 هزارتومان</span>
</div>

JavaScript - Checkbox loop not totalling up prices correctly

When I click on the checkbox at the top, it puts a '0' in the total box, so I know that it is connected correctly, however I think there is a problem in the logic in the loop. One of the elements in html looks like this.
const form = document.getElementById('bookingForm');
const total = document.getElementById('total');
const checkboxes = document.querySelectorAll('input[data-price][type=checkbox]');
const cbamount = checkboxes.length;
document.getElementsByName('event[]')[0].onclick = function() {
totalPrice()
};
function totalPrice() {
let totalprice = 0;
for (let i = 0; i < cbamount; i++) {
const box = checkboxes[i];
if (box.checked) {
box.dataset.price = totalprice + box.dataset.price;
} //if
} //for
document.getElementsByName("total")[0].value = totalprice;
}
<span class="eventTitle">Carmen </span>
<span class="eventStartDate">2020</span>
<span class="eventEndDate">2020</span>
<span class="catDesc">T</span>
<span class="venueName">Mill </span>
<span class="eventPrice">3</span>
<span class="chosen"><input type="checkbox" name="event[]" value="11" data-price="35.00"></span>
<section id="Cost">
<h3>Total</h3>
Total <input type="text" name="total" size="20" readonly="">
</section>
You have no total in the code you provided.
I would personally use ID when only having one element and if more, use relative addressing and/or delegation
const form = document.getElementById('booking');
const total = document.getElementById('total');
document.getElementById("booking").addEventListener("click", function(e) {
if (e.target.name === "event[]") {
let totalprice = 0;
[...document.querySelectorAll('input[data-price][type=checkbox]')].forEach(function(box) {
if (box.checked) {
totalprice += +box.dataset.price;
} //if
})
document.querySelector("[name=total]").value = totalprice.toFixed(2);
}
})
<form id="booking" method="get">
<section id="book">
<h2>Select Events</h2>
<div class="item">
<span class="eventTitle">Carmen </span>
<span class="eventStartDate">2020</span>
<span class="eventEndDate">2020</span>
<span class="catDesc">T</span>
<span class="venueName">Mill </span>
<span class="eventPrice">3</span>
<span class="chosen"><input name="event[]" type="checkbox" value="11" data-price="35.00"></span>
</div>
<div class="item">
<span class="eventTitle">Ash</span>
<span class="eventStartDate">202</span>
<span class="eventEnd">2020-12-31</span>
<span class="catD">Exhib</span>
<span class="venueNa">The Biy</span>
<span class="eventPr">0.00</span>
<span class="chosen"><input type="checkbox" name="event[]" value="17" data-price="10.00"></span>
</div>
</section>
<section id="Cost">
<h3>Total</h3>
Total <input type="text" name="total" size="20" readonly="">
</section>
</form>

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).

calculate the sum of shopping cart

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);

Categories