Fred J.
Fred J.

Reputation: 6019

Total value attribute for all checked boxes

This jQuery code tries to total all the value of the input elements with class = valid that are checked. How is it done? thx

Template.checkbox.events({
  'click .valid': () => {
    $("input.valid:checked").each( function () {
      console.log(this);  //total them here 
    })
  }
});
<template name="checkbox">
  <div class="checkbox-container">
    <div class="checkbox">
      <label class="check">
        <input class="valid" type="checkbox" name={{name}} value={{value}} checked={{checked}}>{{label}}
        <input class="count" type="checkbox" name={{name}} value={{value}} checked={{checked}}>
      </label>
    </div>
  </div>
</template>

Upvotes: 0

Views: 37

Answers (2)

tymeJV
tymeJV

Reputation: 104775

Your selector is good, now you just need to increment a value each loop. You can use .map to get all the values to an array, then reduce it:

var total = $("input.valid:checked").map( function () {
  return this.value;
}).get().reduce(function(t, number) {
    return t += parseInt(number, 10);
}, 0);

Upvotes: 1

Scott Marcus
Scott Marcus

Reputation: 65808

var total = null;
Template.checkbox.events({
  'click .valid': () => {
    $("input.valid:checked").each( function () {
      total += parseFloat(this.value);
    })
  }
});
console.log(total);

Upvotes: 0

Related Questions