EnlargingHippo EnlargingHippo - 2 months ago 7
Javascript Question

JS Function Trouble - Reutning NaN

I am trying to make a salary calculator that takes the input of hours, multiplies it by the hourly rate and then gets multiplied by 52 for an annual salary. My issue comes when I try to run my function to get the salary. Whenever I press it, I am met with an NaN. Any help would be greatly appreciated

<form name="salInput">
Hourly Rate <input type ="text" id="HourlyRate" /><br />
Hours per Week <input type ="text" id="HoursPerWeek" /><br />
</form>


<script>
var a = parseFloat(salInput.HourlyRate.value);
var b = parseFloat(salInput.HoursPerWeek.value);
var c = a*b*52;
function salCalc(){

document.getElementById("change").innerHTML = c;
}
</script>


<button onclick="salCalc()">Calculate</button>
<p id="change"></p>

Answer

Set value of a, b and c every time the function executes. You are just setting it once. Also in place of dot notation for accessing form elements, get their value by ID.

function salCalc() {
     var a = parseFloat(document.getElementById("HourlyRate").value);
     var b = parseFloat(document.getElementById("HoursPerWeek").value);
     var c = a * b * 52;
     document.getElementById("change").innerHTML = c;
}
<form name="salInput">
  Hourly Rate
  <input type="text" id="HourlyRate" />
  <br />Hours per Week
  <input type="text" id="HoursPerWeek" />
  <br />
</form>
<button onclick="salCalc()">Calculate</button>
<p id="change"></p>