简体   繁体   中英

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>
<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 :)

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>
    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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM