[英]Javascript calculator as users type numbers
I'm a noob at Javascript, but I'm trying to implement something on my website where users can type a quantity, and the subtotal updates dynamically as they type. 我是Javascript的菜鸟,但我正在尝试在我的网站上实现一些用户可以输入数量的内容,并且小计在输入时动态更新。 For example: if items are 10 dollars each, and a user types 5 in the text field I would like it to show $50 next to the text box.
例如:如果项目每个10美元,而用户在文本字段中键入5,我希望它在文本框旁边显示50美元。 Pretty simple multiplication, but I don't know how to do it with Javascript.
非常简单的乘法,但我不知道如何使用Javascript。 I think onKeyPress somehow?
我想onKeyPress不知何故? Thanks!
谢谢!
Assuming the following HTML: 假设以下HTML:
<input type="text" id="numberField"/>
<span id="result"></span>
JavaScript: JavaScript的:
window.onload = function() {
var base = 10;
var numberField = document.getElementById('numberField');
numberField.onkeyup = numberField.onpaste = function() {
if(this.value.length == 0) {
document.getElementById('result').innerHTML = '';
return;
}
var number = parseInt(this.value);
if(isNaN(number)) return;
document.getElementById('result').innerHTML = number * base;
};
numberField.onkeyup(); //could just as easily have been onpaste();
};
Here's a working example . 这是一个有效的例子 。
You should handle 'onkeyup' and 'onpaste' events to ensure you capture changes by keyboard and via clipboard paste events. 您应该处理'onkeyup'和'onpaste'事件,以确保您通过键盘和剪贴板粘贴事件捕获更改。
<input id='myinput' />
<script>
var myinput = document.getElementById('myinput');
function changeHandler() {
// here, you can access the input value with 'myinput.value' or 'this.value'
}
myinput.onkeyup = myinput.onpaste = changeHandler;
</script>
Similarly, use getElementById
and the element's innerHTML
attribute to set the contents of an element when you want to show the result. 类似地,当您想要显示结果时,使用
getElementById
和元素的innerHTML
属性来设置元素的内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.