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>
the penalty
(parseFloat( money ) || 0)
does not make q items smaller than0
become0
(for example-1
will continue to be-1
), only values that can be converted tofalse
, you can see better on https://en.wikipedia.org/wiki/Short-circuit_evaluation– Luan Castro
@Luancastro Thanks.
– Klaider