1

I have a simple parse to get the sum of a collection of textareas. It works fine, but if there's no value placed in the field, then the calculation just doesn't run.

How can I make the default value 0 without having the contents actually have to be 0? Like, I don't want the fields to load up with a 0 already waiting in the box - I just want the formula to not worry about empty fields.

Here's the jQuery:

jQuery(document).ready(function(){

  jQuery(".button1").click(function(){

  var set1 = function() {
  var calc1 = 0;
  $('.calc1').each( function(index,item) {
    calc1 += parseInt(jQuery(item).val());
  });
  $('.result1').html(calc1);
}
set1();

  });

});

The codepen can be seen here if you'd like to get a better idea: https://codepen.io/JTBennett/pen/NENMdP

I appreciate any help with this! I know it's probably a stupid mistake, but I've tried a few different things and not gotten anywhere yet.

  • Possible duplicate of [Replace a value if null or undefined in JavaScript](https://stackoverflow.com/questions/1011317/replace-a-value-if-null-or-undefined-in-javascript) – Heretic Monkey Nov 08 '18 at 22:39

3 Answers3

5

Try parseInt(jQuery(item).val() || 0). The || operator will return the second value if the first is falsey. Therefore if the value is empty, it will try to parse '0' which it will successfully.

1

Just make an if statement that looks for an empty field and then replace it with 0.

  $('.calc1').each( function(index,item) {
    var itemValue = jQuery(item).val();
    if (itemValue === "") {itemValue = 0;}
    calc1 += parseInt(itemValue);
  });
Nosajimiki
  • 1,073
  • 1
  • 9
  • 17
0

You can just replace your line with this:

calc1 += parseInt(jQuery(item).val() || 0);
V. Sambor
  • 12,361
  • 6
  • 46
  • 65