0

I have a function that sums my values and everything works fine, but only when all inputs have a value entered. However, I would like default to have 0 assigned to it.so that the function works when at least one value is given . How to do it ?.

var DeductiblepercentageM = thisPointer.entity.getValue('number.DeductiblepercentageM[' + i + ']');
    
            var InsuranceLimitM = thisPointer.entity.getValue('number.InsuranceLimitM[' + i + ']');
        
            var insuranceRaitingM = thisPointer.entity.getValue('number.insuranceRaitingM[' + i + ']');
    
            var InsurerNumberM = thisPointer.entity.getValue('number.InsurerNumberM[' + i + ']');
            DeductiblepercentageM = DeductiblepercentageM.replace(",", ".");
            DeductiblepercentageM = parseFloat(DeductiblepercentageM)
            InsuranceLimitM = InsuranceLimitM.replace(",", ".");
            InsuranceLimitM = parseFloat(InsuranceLimitM)
            insuranceRaitingM = insuranceRaitingM.replace(",", ".");
            insuranceRaitingM = parseFloat(insuranceRaitingM)
            InsurerNumberM = InsurerNumberM.replace(",", ".");
            InsurerNumberM = parseFloat(InsurerNumberM)
    
        
            //log the outcome of decimal separator change

            var positionSum = +(DeductiblepercentageM + InsuranceLimitM +insuranceRaitingM + InsurerNumberM);
    
            jQ('[id="DeductibleM[' + i + ']"]').val(positionSum);

            thisPointer.entity.setValue('DeductibleM[' + i + ']', positionSum);
            thisPointer.entity.mergeLocal(true);

            if (totalSum != "NaN") {
                totalSum = +(totalSum + positionSum).toFixed();
            }
        }
        else {
            totalSum = "-";
        }
Cjmarkham
  • 9,484
  • 5
  • 48
  • 81
Gajka42
  • 35
  • 6
  • When you are calling `.getValue(...)`, just add `|| 0` at the end so that empty strings (which are falsy) will get a value of `0`, e.g. `var InsuranceLimitM = thisPointer.entity.getValue('number.InsuranceLimitM[' + i + ']') || 0;` – Terry Oct 31 '22 at 19:16
  • To check for null, undefined, or 0 `a += myVal ? myVal : 0;` – ControlAltDel Oct 31 '22 at 19:17
  • 1
    Does this answer your question? [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 Oct 31 '22 at 19:18
  • If you're targeting modern browsers, use the nullish coalescing operator `??`, which ignores values that are falsy. Unless you want 0 when you get falsy values, then use `||` as @Terry suggests. – Heretic Monkey Oct 31 '22 at 19:21

1 Answers1

0

According to @Terry

var InsuranceLimitM = thisPointer.entity.getValue('number.InsuranceLimitM[' + i + ']') || 0;

adding || 0 to the end of the code helps and makes the code count right away

Henryc17
  • 851
  • 4
  • 16
Gajka42
  • 35
  • 6