将两个变量相乘,并将total插入到输入的JavaScript中.点击命令

Multiplying two variables and inserting total into input JavaScript on.click command

本文关键字:输入 插入 JavaScript 命令 total 并将 两个 变量      更新时间:2023-09-26

我有两个输入宽度和高度来计算三角形的面积。当你在每个输入中键入宽度和高度的数字时,我需要一个提交按钮来乘以宽度x高度,并在输入中插入总面积。

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;
     }
  • 两者的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>

您有一个id为"total"的错误元素。按钮不应该,输入应该。

您应该按Id选择元素,然后将结果作为值分配给元素

因此,在您的情况下,应该是:从按钮中删除总id。现在您只有一个具有唯一id"total"的元素document.getElementById("txtArea").value=结果;

  1. id="total"有两个元素。将按钮上的id属性更改为其他属性或将其删除
  2. 您在javascript函数的最后一行将myResult大写。javascript中的大小写很重要

您可以编写return myResult,然后calculateArea函数将返回myResult。

此外,"id"用于唯一的元素-对多个元素使用"class"。