在我的javascript函数中,我试图从表单用户输入到我创建的函数并输出答案的值

In my javascript function I am trying to get the values from a form user input to a function I created and the output the answer

本文关键字:函数 创建 输入 答案 输出 用户 javascript 我的 表单      更新时间:2023-09-26

我正试图从我的表单中获取值为函数并返回值这是我的函数

function createInput(){
  var weight;
  weight = document.bmiCalc.weight.value;
  var height = getElementById('height').value;
  input.onclick = function calcBMI()
    {
    // calculate users BMI
    var BMI = weight * 703 / Math.pow(height, 2);
  return BMI;
  }
  document.getElementById("BMI").appendChild();
}

这是我的HTML页面的表单代码

    <form id="bmiCalc">
      <h2> Calculate your Current BMI</h2>
        <p><label> Please enter your weight in lbs: <input type="text" name = "weight" id=   "weight"></label></p>
        <p><label>  Please enter your height in inches: <input type="text" name ="height" id="height"></label>
          <button type="submit">Submit</button></p>
        <p><label> Your current BMI is: <input name="BMI" id="BMI"></label></p>
     </form>

更改html和js:

http://jsfiddle.net/CQxnx/

html:

<h2> Calculate your Current BMI</h2>
<label> Please enter your weight in lbs:</label> <input type="text" name="weight" id="weight">
<br />    
<label>  Please enter your height in inches:</label> <input type="text" name="height" id="height">
    <br />
    <input type="button" value="calculate" onclick="calcBMI();" />
    <br />
 <div id="msg"></div>

js:

function calcBMI(){
    var weight = document.getElementById('weight').value;
    var height = document.getElementById('height').value;
     // calculate users BMI
    var BMI = weight * 703 / Math.pow(height, 2);
    var msg = document.getElementById('msg');
    msg.innerHTML = 'Your current BMI is:' + BMI;
}

您似乎有点偏离,但您从未真正调用createInput函数。即使在那之后,你也不会附加输入按钮。没有BMI ID元素,createInput将计算重量/高度,因为它们是当它被调用,而不是当按钮被点击。

相反,您应该首先将按钮放在DOM中,并将计算函数绑定到它。

document.getElementById('calculate').addEventListener('click', function () {
    document.getElementById("BMI").textContent =
        document.getElementById('weight').value * 703 /
        Math.pow(document.getElementById('height').value, 2);
});
http://jsfiddle.net/fsKNb/