2016-08-02 47 views
0

我有兩個輸入寬度和高度來計算三角形的面積。當你在寬度和高度的每個輸入中鍵入數字時,我需要一個提交按鈕來乘以寬度x高度並將總面積插入到輸入中。乘以兩個變量並將總數插入輸入JavaScript on.click命令

HTML:

<p id="instructions" class="Main">Enter the width and height of your triangle to calculate the area.</p> 

<!--Main div--> 
<form id="mainform"> 
     Width (b): 
      <input type="Text" id="width" placeholder="width" > 
    <div> 
     Height(h): 
      <input type="text" id="height" placeholder="height"> 
    </div> 
      <button type="button" id="total" onclick="calculateArea()">Calculate Area</button> 
       </form> 

       <!--Divider--> 
       <form> 
        <div id="divider"> 
        </div> 
        <div id="area"> 
         The area is: 
         <input type="text" name="txtarea" id="total"> 
        </div> 
       </form>  
     </div> 

的JavaScript:

function calculateArea() { 
    var width = document.getElementById('width').value; 
    var height = document.getElementById('height').value; 
    var total = document.getElementById('total'); 
    total.value = width * height; 
    } 
+0

JAVA!= JAVASCRIPT – shmosel

回答

0

你有id爲 「總」 的錯誤的元素。 該按鈕不應該,輸入應該。

0

你應該選擇由ID的元素,然後將結果作爲分配價值的元素

所以你的情況,應該是: 取出總從按鈕的ID。現在,您只有一個元素具有唯一標識'total' document.getElementById(「txtArea」)。value = result;

1
  • 兩者都具有相同的id'total'。我已將其命名爲「產品」。
  • total.value = myResult;還有一個錯字錯誤。

function calculateArea() { 
 
    var width = document.getElementById('width').value; 
 
    var height = document.getElementById('height').value; 
 
    var total = document.getElementById('product'); 
 
    var myResult = width * height; 
 
    total.value = myResult; 
 
}
<p id="instructions" class="Main">Enter the width and height of your triangle to calculate the area.</p> 
 

 
<!--Main div--> 
 
<form id="mainform"> 
 
    Width (b): 
 
    <input type="Text" id="width" placeholder="width"> 
 
    <div> 
 
    Height(h): 
 
    <input type="text" id="height" placeholder="height"> 
 
    </div> 
 
    <button type="button" id="total" onclick="calculateArea()">Calculate Area</button> 
 
</form> 
 

 
<!--Divider--> 
 
<form> 
 
    <div id="divider"> 
 
    </div> 
 
    <div id="area"> 
 
    The area is: 
 
    <input type="text" name="txtarea" id="product"> 
 
    </div> 
 
</form> 
 
</div>

+1

感謝您的幫助! –

0
  1. 您有id="total"兩個元素。將按鈕上的id屬性更改爲其他內容或將其刪除。
  2. 您在javascript函數的最後一行大寫了myResult。使用javascript處理事宜。
0

您可以編寫return myResult,然後calculateArea函數將返回myResult。

另外,「id」用於唯一元素 - 對於多個元素使用「class」。