I have to do a small calculation using values from form fields with the use of javascript. The formula for the calculation is below:
totalIncome = income1 + income2 *0.7 + income3/48 + (income4 * 0.7)/48;
The values of income1
, income2
, income3
and income4
can be zero and the fields can be empty.
My code is below:
<tr id="row">
<td>No. of Dependant(s)</td>
<td><input type="text" id="income1" value=""></td>
<td><input type="text" id="income2" value=""></td>
<td><input type="text" id="income3" value=""></td>
<td><input type="text" id="income4" value=""></td>
<td><input type="text" id="totalIncome" readonly></td>
</tr>
The formular script I have used for my formula is below:
var income1 = document.getElementById("income1");
var income2 = document.getElementById("income2");
var income3 = document.getElementById("income3");
var income4 = document.getElementById("income4");
var totalIncome = document.getElementById("totalIncome");
var inputs = Array.prototype.slice.call(document.querySelectorAll("td > input"));
inputs.forEach(function(input){
input.addEventListener("blur", function(){
// Always supply the second argument to parseInt() (the radix) so you
// dont' get non-base 10 answers.
totalIncome.value = parseInt(income1.value, 10) + parseInt(income2.value, 10)* 0.7 + parseInt(income3.value, 10)/48 + (parseInt(income4.value, 10)*0.7)/48;
});
});
However, I am not sure why the totalIncome
will become NaN
when some of the fields are empty.