Tim C
Tim C

Reputation: 5714

Why is this simple javascript program not working?

The alert window gives me the message NaN what is wrong? Thanx for all the help

var weight = parseFloat(document.BMI.weight.value)
var height = parseFloat(document.BMI.height.value)

function calcBMI() {
var answer = weight * 703 / (height*height)
return answer;
  }
    </script>


 <form action="" name="BMI">
<input type="text" name="weight" />
<input type="text" name="height" />
<input type="submit" onclick="alert(calcBMI())" />
</form>

Upvotes: -1

Views: 147

Answers (3)

polin
polin

Reputation: 2845

    function calcBMI() {
    var weight = parseFloat(document.BMI.weight.value)
var height = parseFloat(document.BMI.height.value)
var answer = weight * 703 / (height*height)
return answer;
  }
    </script>

There is a problem with local and grobal variable. While you are clicking the button the function is not fetching the value from the textboxes

Upvotes: 0

MonsterTKE
MonsterTKE

Reputation: 3

You need to move your variables into your function call. *Edit.. I was beaten to the punch.

<form action="" name="BMI">
  <input type="text" name="weight" />
  <input type="text" name="height" />
  <input type="submit" onclick="alert(calcBMI())" />
</form>

<script type="text/javascript">

function calcBMI() {
    var weight = parseFloat(document.BMI.weight.value)
    var height = parseFloat(document.BMI.height.value)
    var answer = weight * 703 / (height*height)
    console.log(weight);
    return answer;
}
</script>

Upvotes: 0

asifsid88
asifsid88

Reputation: 4701

<script type="text/javascript">
function calcBMI() {
var weight = parseFloat(document.BMI.weight.value)
var height = parseFloat(document.BMI.height.value)
var answer = weight * 703 / (height*height)
return answer;
  }
    </script>


 <form action="" name="BMI">
<input type="text" name="weight" />
<input type="text" name="height" />
<input type="submit" onclick="alert(calcBMI())" />
</form>

Hopefully it works now :)

Upvotes: 2

Related Questions