Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I add 3 variables if one or two may not have a value?

Tags:

javascript

I have 3 variables that are fed from a form input (type="text"). Each input may or may not be entered by a user. I just want to add the variables together if they have any values entered. The problem is if any of them are left blank on the form I get NaN returned.

I really enjoy figuring these things out but I haven't been able to Google my issue, I'm happy to just be told what to Google to figure this out.

function extrasCalc() {
    var grub = 0;
    var lime = 0;
    var aerseed = 0;

    grub = parseInt(document.getElementById("grubprice").value);
    lime = parseInt(document.getElementById("limeprice").value);
    aerseed = parseInt(document.getElementById("aerseedprice").value);
    var extrasSubtotal = grub + lime + aerseed;

    document.getElementById("sub").value = extrasSubtotal;

    console.log(grub);
    console.log(lime);
    console.log(aerseed);
    console.log(extrasSubtotal);
}

If only 1 or 2 of the variables have a value, I would like them to be totaled. So far all 3 have to have a value for the function to work.

like image 837
user2942346 Avatar asked Nov 26 '25 18:11

user2942346


1 Answers

You could ensure that the values are valid this way:

function extrasCalc() {    
    var grub = +document.getElementById("grubprice").value || 0;
    var lime = +document.getElementById("limeprice").value || 0;
    var aerseed = +document.getElementById("aerseedprice").value || 0;

    var extrasSubtotal = grub + lime + aerseed;

    document.getElementById("sub").value = extrasSubtotal;

    console.log(grub);
    console.log(lime);
    console.log(aerseed);
    console.log(extrasSubtotal);
}

Basically grub, lime and aerseed are assigned 0s, if their corresponding expressions evaluate to "falsy" values.

As a bonus, you could replace parseInt with + prefix, which does the same job and is a bit terser.

like image 156
Alex Lomia Avatar answered Nov 29 '25 08:11

Alex Lomia



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!