I've seen a similar question on SO but my approach is slightly different. I have a textarea
that I want to accept only numbers as an input. Currently all inputs are allowed and the error alert isn't triggered.
我在SO上看过类似的问题,但我的方法略有不同。我有一个textarea,我只想接受数字作为输入。目前允许所有输入,并且不会触发错误警报。
I think the problem may be that the key being pressed isn't being passed into my validate function, but I'm not sure how to do that without using the html onkeypress which I'm trying to avoid using.
我认为问题可能是被按下的键没有被传递到我的验证函数中,但是我不知道如何在不使用我试图避免使用的html onkeypress的情况下这样做。
HTML:
HTML:
<textarea id="noteNumberInput" placeholder="Note number"></textarea>
JS:
JS:
$(document).ready(function () {
var noteNumberInput = document.getElementById("noteNumberInput");
//VALIDATE NOTE NUMBER TEXTAREA
function validate() {
var keycode = (key.which) ? key.which : key.keyCode;
//comparing pressed keycodes
if (keycode < 48 || keycode > 57) {
alert("Please only enter the note number e.g. '1', '2' etc.")
return false;
}
}
noteNumberInput.addEventListener("keypress", validate);
});
1 个解决方案
#1
1
Your function needs the key parameter:
您的函数需要关键参数:
function validate(key) {
....
#1
1
Your function needs the key parameter:
您的函数需要关键参数:
function validate(key) {
....