![](/img/trans.png)
[英]How can I get the value of 2 inputs, calculate them and put the result in another
[英]Get values from inputs, calculate them and show the result
我有以下两个文本输入:
<input type="text" value="" id="width" name="width" />
<input type="text" value="" id="height" name="height" />
在下面是:
<h1>Summ: xxxxxx</h1>
我想用以下数学替换xxxxx:
(width * height) / 2
每当我在宽度或高度输入中输入新值时,求和值都应实时更改。
这有可能吗? 谢谢。
您有多种选择可以做到这一点。 有许多技术框架,库和实现方法。
就我而言(因为我对此更加熟悉),使用JQuery这样更容易。
$('#width, #height').on('input', function(){ var width = $('#width').val(); var height = $('#height').val(); if (width != "" && height != "") $('#result').text(width*height/2); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="number" value="" id="width" name="width" /> <input type="number" value="" id="height" name="height" /> <h1>Result: <span id='result'>0</span></h1>
Obs:我将您的输入字段更改为数字类型,因此用户不会输入非数字数据。
快速解决:
<input type="text" value="" id="width" name="width" />
<input type="text" value="" id="height" name="height" />
<h1 class="calc"></h1>
和:
$('#width, #height').on('input', function () {
var widthInput = $('#width').val()
var heightInput = $('#height').val()
var result = widthInput * heightInput / 2
$('.calc').text(result)
})
您可能想为每个字段放置一个类似1
的占位符值,这样它就不会以0开始计算。而且,它的拼写是“ sum”而不是“ summ”,而且无论如何都不是总和。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.