[英]Get values from inputs, calculate them and show the result
I have these two text inputs: 我有以下两个文本输入:
<input type="text" value="" id="width" name="width" />
<input type="text" value="" id="height" name="height" />
And below there is: 在下面是:
<h1>Summ: xxxxxx</h1>
I want to replace xxxxx with the following math: 我想用以下数学替换xxxxx:
(width * height) / 2
Whenever I type a new value at width or height inputs, the Summ should change realtime. 每当我在宽度或高度输入中输入新值时,求和值都应实时更改。
Is this possible at all? 这有可能吗? Thank you. 谢谢。
You have multiple options to do that. 您有多种选择可以做到这一点。 There are many technologies frameworks, libraries, and ways to do it. 有许多技术框架,库和实现方法。
In my case (as I'm more familiar with this), the easier would be to use JQuery like this. 就我而言(因为我对此更加熟悉),使用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: I changed your input fields to numeric type, so the user won't enter non-numeric data. Obs:我将您的输入字段更改为数字类型,因此用户不会输入非数字数据。
The main pieces of the problem are: 问题的主要部分是:
The relevant functions are val() , change() , and text() respectively. 相关函数分别是val() , change()和text() 。 The examples in the documentation should help you figure out how to piece it all together. 文档中的示例应帮助您弄清楚如何将它们组合在一起。
Quick fix: 快速解决:
<input type="text" value="" id="width" name="width" />
<input type="text" value="" id="height" name="height" />
<h1 class="calc"></h1>
And: 和:
$('#width, #height').on('input', function () {
var widthInput = $('#width').val()
var heightInput = $('#height').val()
var result = widthInput * heightInput / 2
$('.calc').text(result)
})
You might wanna put a placeholder value like 1
for each field so it doesn't begin calculating with a 0. Also, it's spelled "sum" and not "summ", and it's not a sum anyway. 您可能想为每个字段放置一个类似1
的占位符值,这样它就不会以0开始计算。而且,它的拼写是“ sum”而不是“ summ”,而且无论如何都不是总和。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.