Leo Messi
Leo Messi

Reputation: 6186

Combine multiple elements by class in jQuery

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.

Upvotes: 1

Views: 97

Answers (3)

Carsten Massmann
Carsten Massmann

Reputation: 28196

jQuery allows you to do the whole thing as a one-liner:

$("#res").text($(".cart-items .cart-quantity-input").get().reduce((a,c)=>+c.value+a,0))
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="cart-items">
  <input name="a" class="cart-quantity-input" value="12"/> 
  <input name="b" class="cart-quantity-input" value="25"/> 
  <input name="c" class="cart-quantity-input" value="3"/> 
</div>
<div class="cart-items">
  <input name="d" class="cart-quantity-input" value="7"/> 
  <input name="f" class="cart-quantity-input" value="3"/> 
  <input name="f" class="cart-quantity-input" value="4"/> 
</div>
<div class="cart-items">
  <input name="g" class="cart-quantity-input" value="1"/> 
  <input name="h" class="cart-quantity-input" value="5"/> 
  <input name="i" class="cart-quantity-input" value="2"/> 
</div>
<div id="res"></div>

Upvotes: 0

trincot
trincot

Reputation: 350310

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

Upvotes: 1

Leo Messi
Leo Messi

Reputation: 6186

Based on @trincot comment:

 const totalQuantity = [...$('.cart-items .cart-quantity-input')]
    .map((subtotalElm) => Number(subtotalElm.value))
    .reduce((a, b) => a + b, 0);
  $('.items-number').text(totalQuantity + ' items');

Upvotes: 1

Related Questions