I changed the sum line to
distanceTravelled += distances[i];
I also swapped the dynamic values with temporary ones, it displayed $150
, which is the expected result (and nothing to do with brackets as mentioned by @cbp).
function calcRate() {
var engineRate = 10;
var distanceTravelled = 0.0;
var distances = new Array();
distances[0] = 1;
distances[1] = 2;
distances[2] = 3;
distances[3] = 4;
distances[4] = 5;
for (var i = 0; i < distances.length; i++) {
if (!isNaN(distances[i])) {
distanceTravelled += distances[i];
}
}
alert("$" + distanceTravelled * engineRate);
}
calcRate();
I then swapped in the jQuery selector for the output text box, it displays $150
:
<input name="reimbursement" />
Assuming the engine rate are radio buttons, I proceeded to add them in:
<input type="radio" name="enginesize" value="10" />10<br>
<input type="radio" name="enginesize" value="100" />100<br>
<input type="radio" name="enginesize" value="1000" />1000<br>
Clicking on any of them displays the expected results: $150, $1500, $15000
I can only conclude that the selector for field_Distance
is wrong:
jQuery("#field_Distance1")
You might want to use this instead to get the name of the field, as #
means you are getting the ID attribute instead, which is probably missing.
jQuery("input[name=field_Distance1]")
Why is it displaying $0 then? As the selector is wrong, the array now contains NaN
values. distanceTravelled remains as 0.0
after the for-loop as !isNaN(distances[i])
returns false, skipping over the sum. In the end, anything multiplied by 0 returns 0.