[英]execute JS function on keystroke
I have created a function that when the use fills in the two inputs comm and hour it populated the result in another input called phone. 我创建了一个函数,当用户在两个输入中输入comm和hour时,它将结果填充到另一个称为phone的输入中。
calculate = function()
{
var comm = document.getElementById('comm').value;
var hour = document.getElementById('hour').value;
document.getElementById('phone').value = Math.round(comm*hour*phone/60);
}
At the moment if you type in comm and hour and then you click outside the input it calculates the result in phone. 目前,如果您输入comm和hour,然后在输入之外单击,它将在电话中计算结果。
What I am trying to achieve is to calculate at the moment you type on any of the two fields. 我想要实现的是在您在两个字段中的任何一个上键入时进行计算。
I have tried to find something that can help me here, but with no luck. 我试图在这里找到可以帮助我的东西,但是没有运气。 Any advice?
有什么建议吗?
Look into onkeydown
. 查看
onkeydown
。 Something like the following code. 类似于以下代码。
document.onkeydown = calculate = function()
{
var comm = parseFloat(document.getElementById('comm').value);
var hour = parseFloat(document.getElementById('hour').value);
document.getElementById('phone').value = Math.round(comm*hour*phone/60);
}
This will call that function whenever a key is pressed on the page. 只要在页面上按下一个键,就会调用该函数。
As @CharlieFish answer Use document.onkeydown
to call event on key down and use parseFloat
to convert your values to float 作为@CharlieFish答案使用
document.onkeydown
在按下按键时调用事件,并使用parseFloat
将值转换为float
document.onkeydown = calculate = function()
{
//hope you have define phone value
var comm = parseFloat(document.getElementById('comm').value);
var hour = parseFloat(document.getElementById('hour').value);
document.getElementById('phone').value = Math.round(comm*hour*phone/60);
}
document.body.onkeypress(function(){
// invoke your function here calculator()
// additional logic can we added here too.
})
If you want it to start working immediately use a IIFE (immediately invoked function expression) and add an event listener for 'keyup' so it will fire once the value in the input field has been set: 如果您希望它立即开始工作,请使用IIFE(立即调用的函数表达式)并为“ keyup”添加事件侦听器,以便一旦在输入字段中设置了值便会触发:
(function(){
document.getElementById('foo').addEventListener('keyup',function(){
//add your logic here
console.log('someone pressed a key!');
});
}());
...just remember to parseFloat the values in your example before you try to calculate, as when you get them from the element they will be typeof string
... ...只是记得在尝试计算之前先对示例中的值进行浮点运算,因为当您从元素中获取它们时,它们将是
typeof string
...
so value = parseFloat(value);
所以
value = parseFloat(value);
I think what you need is trigger calculate function at text change event, just try this 我认为您需要的是在文本更改事件中触发计算功能,只需尝试一下
<input type="text" id="comm" onchange="calculate();"/>
<input type="text" id="hour" onchange="calculate();"/>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.