Result of calculation in JS returning R$ Nan

Asked

Viewed 494 times

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 he does not choose the required option returns NaN.

How can I fix this?

This is 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>

2 answers

1


In this line of your code

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

you have to create a fallback for when that input is empty. This is because later you will use parseFloat() and when money is empty it gives NaN. Corrects for:

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

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

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

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

The ternary works like this:

condição ? caso verdadeiro : caso falso;

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

id('campo5').value = internet && telefone ? 'R$ ' [etc...] : '';

0

Add the || (or) on that line (where you call the parseFloat):

return parseFloat( money )*100;

Example:

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

Now, if the parseFloat( money ) return NaN, will be returned a 0 in place.

  • 1

    the penalty (parseFloat( money ) || 0) does not make q items smaller than 0 become 0 (for example -1 will continue to be -1), only values that can be converted to false, you can see better on https://en.wikipedia.org/wiki/Short-circuit_evaluation

  • 1

    @Luancastro Thanks.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.