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.

1

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

4 Comments

This is correct, but in order to do less work you can use the numeric 0 instead of a string.
Definitely cleaner than my answer +1
@zfrisch Good catch, forgot the Javascript parseInt works on numeric values as well.
Thank you very much! I really need to learn how to do this stuff properly, I feel like I'm missing a foundation since I never went to school for this stuff :|
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);
  });

Comments

0

You can just replace your line with this:

calc1 += parseInt(jQuery(item).val() || 0);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.