I want to get the numeric values from some fields and add their value to a sum and put that sum value into another element.
It works nice if they are separate lines:
var quantity0 = parseFloat($('#0').find('.cart-quantity-input').val());
var quantity1 = parseFloat($('#1').find('.cart-quantity-input').val());
var quantity2 = parseFloat($('#2').find('.cart-quantity-input').val());
var totalQuantity = quantity0 + quantity1 + quantity2;
$('.items-number').text(totalQuantity + ' items');
But when they are combined there must be something that I miss because it doesn't work:
const totalQuantity = [...$('.cart-items .cart-quantity-input')]
.map((subtotalElm) => Number(subtotalElm.textContent.val()))
.reduce((a, b) => a + b, 0);
$('.items-number').text(totalQuantity + ' items');
There is one difference, instead of taking the ids (0,1,2) it takes the parent class cart-items
but the error is not from there.
input
elements have no textContent
property, and chaining a .val()
method will produce an exception.
As a side note: with $.map
you avoid one extra iteration, and you can use unary +
instead of Number
So:
const totalQuantity = $.map($('.cart-items .cart-quantity-input'), input => +input.value)
.reduce((a, b) => a + b, 0);
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments