[英]Key-Press event listener when checking textarea input in Javascript
I want to check two conditions for every button press on the keyboard inside a textarea
: 我想检查文
textarea
键盘上的每个按钮按下的两个条件:
1) If it's a number then add it to the text area. 1)如果是数字,则将其添加到文本区域。
2) If it's anything else push an alert to the user. 2)如果还有其他情况,请向用户发送警报。
The textarea
tag in the html is: html中的
textarea
标签是:
<textarea id="input" placeholder="EnterInput"></textarea>
What I wrote inside the JS file is: 我在JS文件中写的是:
document.getElementById("input").addEventListener("keypress", checkInput(e));
function checkInput(keyPressed){
if(keyPressed < 48 || keyPressed > 57){
alert("Wrong input! The charcted entered is not a number.");
}
}
You're immediately invoking your listener function by having the ()
您可以通过
()
立即调用您的监听器功能
document.getElementById("input").addEventListener("keypress", checkInput(e))
^^ INVOKED!
event
will automatically be passed to your function, so simply omit that: event
将自动传递给您的函数,因此只需忽略以下内容:
document.getElementById("input").addEventListener("keypress", checkInput)
Also, the which
property of event
stores the key code (on most browsers, as @TJCrowder pointed out, older browsers may use the keyCode
property): 此外,
which
的性能event
存储的密码(大多数浏览器上,如@TJCrowder指出,旧的浏览器可以使用keyCode
属性):
function checkInput(event) {
var keyCode = event.hasOwnProperty('which') ? event.which : event.keyCode;
//Now check
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.