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>