1

I was wondering how will I be able to get the values from the array generated by the code and then be able to add them in a single variable:

      var selector = 'input[name^="Textbook"]';
        $(selector).on('click', function() {
          var checked = $(selector + ':checked').map(function() {
            return {
              'type': this.type,
              'value': this.value
            };
          }).get().filter(function(o) {
            return '-1' !== o.value; // skip if value = -1(No)
          });
          console.log('checked inputs', checked);
        });
      }

I have checked functions in javascript such as .reduce which according to developer.mozila.org "reduces it to a single value". Though my goal is to add only the numeric values and the array has non-numeric values as well. How can i accomplish this? Thanks!

EDIT: Here's an example of an array that the code above through the variable "checked" could output:

Output of script above

My goal is to add all the 'value' data and ignore the non-numeric ones.

EDIT2: Here's the HTML code. Not too sure how i could show you a working version as it relies on PHP as well and sites such as jsfiddle doesn't support it.

                  <label class="radio-inline">
                    <input form="ES4S" type="radio" name="Supplies1" value="'.$Result[$i]['ID'].'"> Yes
                    <input form="ES4S" type="hidden" style="display:none" value="'.$Result[$i]['ID'].'" name="SuppliesID'.$i.'">
                  </label>
                  <label class="radio-inline">
                    <input form="ES4S" type="radio" name="Supplies1" value="-1">No
                  </label>
4
  • It looks like your function depends on the HTML - can you give an example of the HTML and the desired output? Commented Jun 11, 2018 at 4:10
  • Better to create a working snippet of your code along with desired output. Commented Jun 11, 2018 at 4:12
  • how's the html looks like? I am not sure when and how the user input.
    – Wils
    Commented Jun 11, 2018 at 4:19
  • Fill in the PHP bits with what would be rendered (e.g., copy the HTML of the rendered page, not your code)
    – vol7ron
    Commented Jun 11, 2018 at 4:53

3 Answers 3

2

Use reduce and check if the value is numeric when you're factoring it into the sum:

var selector = 'input[name^="Textbook"]';

$(selector).parent().on('click', selector, function() {
  var checked = $(`${selector}:checked`).get()
  
  var sum = checked.reduce((c,p)=>{
    if (!(isNaN(+p.value)))
      c += +p.value;
    return c;
  },0)
  
  console.clear();
  console.log('sum',sum);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<label class="radio-inline">
  <input form="ES4S" type="radio" name="Textbook" value="MPM Charge"> Yes
  <input form="ES4S" type="hidden" style="display:none" value="MPM Charge" name="Textbook">
</label>
<label class="radio-inline">
  <input form="ES4S" type="radio" name="Textbook" value="100">No
</label>

<br>

<label class="radio-inline">
  <input form="ES4S" type="radio" name="Textbook2" value="MPM Charge"> Yes
  <input form="ES4S" type="hidden" style="display:none" value="MPM Charge" name="Textbook2">
</label>
<label class="radio-inline">
  <input form="ES4S" type="radio" name="Textbook2" value="300">No
</label>

There's no need to do filter first, since that would require iterating over your array twice. Using reduce does everything in one pass. The unary operator (+) is used to convert stringed numerics into a number to ensure isNaN tests positive.

7
  • Cheers! That worked well for me. This code made a lot more sense to me too! :)
    – DeathKing
    Commented Jun 11, 2018 at 5:17
  • A lot of improvements could be made, especially in variable names, but it comes down to preference. Good luck on your journey in finding out what works best for you
    – vol7ron
    Commented Jun 11, 2018 at 5:20
  • Hm i wonder if i can make this piecevof code run every second to check for checked input boxes instead of being triggered only when a form is clicked? @vol7ron
    – DeathKing
    Commented Jun 11, 2018 at 5:22
  • Check setInterval
    – vol7ron
    Commented Jun 11, 2018 at 5:22
  • I actually have.. but since its on 'click' it wont update every second regardless the interval value
    – DeathKing
    Commented Jun 11, 2018 at 5:29
1

You need to filter by is number then use reduce to get sum of the list

var priceList = [{value:"190"}, {value:"180"}, {value:"Charge"}];

//shorthand code

console.log(priceList.map(n => Number(n.value)).filter(n => !isNaN(n)).reduce(function(a, b) { return a + b; }));

//full code

priceList =priceList.map(n => Number(n.value));
priceList = priceList.filter(n => !isNaN(n));
let priceSum = priceList.reduce(function(acc, val) { return acc + val; });
console.log(priceSum);

3
  • Hm the array above has 2 sets of variables (refer to the image i uploaded). Was wondering how to get what value. :)
    – DeathKing
    Commented Jun 11, 2018 at 4:29
  • I have updated my code to work with 2 sets of variables Commented Jun 11, 2018 at 4:33
  • @DeathKing can you please check and if any problem let me know Commented Jun 11, 2018 at 4:34
0
const checked = [{"type":"radio","value":"100"},{"type":"checkbox","value":"MPM Charge"},{"type":"radio","value":"100.25"},{"type":"radio","value":"100"},{"type":"radio","value":"MPM Charge"},{"type":"radio","value":"100.5"},{"type":"radio","value":"100"},{"type":"radio","value":"MPM Charge"}]

Array.prototype.sum_values = function (prop, i, running_total = 0) {

  const array = Object.assign([], this)

  if (i === 0) {
    return running_total
  } else {
    const val = array[i - 1][prop] // property you want to add up
    const num = Number(val) // convert string to number
    if (isNaN(num)) { // if converted string in not a number
      return array.sum_values(prop, i - 1, running_total) // add nothing
    } else {
      return array.sum_values(prop, i - 1, running_total + num) // add number
    }

  }

}

const test = checked.sum_values('value', checked.length)
console.log(test) // 500.75

// Place the function where your checked array is console logged
var selector = 'input[name^="Textbook"]';
$(selector).on('click', function() {
  var checked = $(selector + ':checked').map(function() {
    return {
      'type': this.type,
      'value': this.value
    };
  }).get().filter(function(o) {
    return '-1' !== o.value; // skip if value = -1(No)
  });
  let sum = checked.sum_values('value', checked.length)
  console.log('checked inputs', sum);
  return sum
})

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.