我有这两个文本输入:
<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>
观察:我将您的输入字段更改为数字类型,因此用户不会输入非数字数据。
关于javascript - 从输入中获取值,计算它们并显示结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31751375/