Calculation result in JS returning R $ NaN

0

I made a calculation form using JS. The point is that there are fields that are mandatory, where the user is required to choose an option with value because the calculation is combined. When it does not choose the required option it returns NaN .

How can I fix this?

Here's my code:

<script type="text/javascript">
    String.prototype.formatMoney = function() {
        var v = this;

        if (v.indexOf('.') === -1) {
            v = v.replace(/([\d]+)/, "$1,00");
        }

        v = v.replace(/([\d]+)\.([\d]{1})$/, "$1,$20");
        v = v.replace(/([\d]+)\.([\d]{2})$/, "$1,$2");
        v = v.replace(/([\d]+)([\d]{3}),([\d]{2})$/, "$1.$2,$3");

        return v;
    };

    function id(el) {
        return document.getElementById(el);
    }

    function getMoney(el) {
        var money = id(el).value.replace(',', '.');
        return parseFloat(money) * 100;
    }

    function soma() {
        var total = getMoney('internet') + getMoney('wifi');
        id('campo5').value = 'R$ ' + String(total / 100).formatMoney();
    }

</script>

Result field:

<input type="text" class="bd-form-input" name="campo5" readonly id="campo5" />

Botton:

<div>
    <a href="#" onclick="soma()" value="Calcular Plano" title="Clique para calcular seu plano">calcular plano</a>
</div>
    
asked by anonymous 04.08.2016 / 20:37

2 answers

1

In this line of your code

var money = id( el ).value.replace( ',', '.' );

You need to create a fallback for when this input is empty. This is because later you will use parseFloat() and when money is empty this gives NaN . Fixes to:

var money = id( el ).value.replace( ',', '.' ) || 0;

Then, in the final sum, to give value only when the value of internet is set, you can do this:

function soma() {
    var inet = getMoney('internet');
    var total = inet + getMoney('wifi');
    id('campo5').value = inet ? 'R$ ' + String(total / 100).formatMoney() : '';
}

So with this ternary in the last line it checks to see if the inet has value, if it does not jump to after : and uses an empty string '' .

ternary works like this :

condição ? caso verdadeiro : caso falso;

So if you have more conditions you can do using this logic

id('campo5').value = internet && telefone ? 'R$ ' [etc...] : '';
    
04.08.2016 / 22:41
0

Add operator || (or) to this line (where you call parseFloat ):

return parseFloat( money )*100;

Example:

return (parseFloat( money ) || 0) * 100;

Now, if parseFloat( money ) returns NaN , a 0 is returned instead.

    
04.08.2016 / 22:20