2016-03-06 180 views
2

我想從html中獲取兩個數字,並使用javascript返回兩者的總和,但是我的num1和num2包含HTMLInputElement ??在HTML中顯示計算結果(javascript)

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

回答

1

您還沒有解析,並增加來自這兩個輸入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>

+0

感謝片段。這很有用 –