繁体   English   中英

将两个变量相乘并将total插入到输入JavaScript on.click命令中

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

我有两个输入宽度和高度来计算三角形的面积。 当您在宽度和高度的每个输入中键入数字时,我需要一个提交按钮来乘以宽度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.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 = result;

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

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

另外,“ id”用于唯一元素-将“ class”用于多个元素。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM