我试图从html中获取两个数字,并使用javascript返回两者的和,但是num1和num2包含htmlinputtement??
html格式:

<head>
        <script type ="text/javascript" src="functions.js"></script>
    </head>
    <body>
        Value 1: <input type="text" id="tb1" name="tb1"><br/>
        Value 2: <input type="text" id="tb2" name="tb2"><br/>
        Result: <input type="text" id="tb3" name="tb3"><br/>
        <button onclick="validateForm()" Type="button" id="b1" name="b1">Go</button>
    </body>

javascript代码:
function validateForm() {
    var x = document.getElementById("tb1");
    var y = document.getElementById("tb2");
    if (x == null || x == "" || y == null || y == "")
    {
        alert("Value cannot be empty");
        return false;
    }
    else {
        //myAdd(x,y);
        alert(x + y);
        var num1 = parseFloat(x);
        var num2 = parseFloat(y);
        var total = num1 + num2;
        document.getElementById("tb3").innerHTML = total;
    }
}

最佳答案

您不是从这两个输入解析和添加values,而是从objects本身。因为您的if语句块将never run,因为您正在将objectnull进行比较。此外,您不能设置innerHTMLinput,必须使用.value。请检查下面的代码片段

parseFloat(x) //you must parseFloat(x.value),

document.getElementById("tb3").value = total; //you have to use .value instead of .innerHTML with input

function validateForm() {
  var x = document.getElementById("tb1").value;
  var y = document.getElementById("tb2").value;
  if (x == null || x === "" || y == null || y === "") {
    alert("Value cannot be empty");
    return false;
  } else {
    //myAdd(x,y);

    var num1 = parseFloat(x);
    var num2 = parseFloat(y);
    var total = num1 + num2;
    document.getElementById("tb3").value = total;
  }
}

Value 1:
<input type="text" id="tb1" name="tb1">
<br/>Value 2:
<input type="text" id="tb2" name="tb2">
<br/>Result:
<input type="text" id="tb3" name="tb3">
<br/>
<button onclick="validateForm()" Type="button" id="b1" name="b1">Go</button>

09-30 08:51