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.
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:
<textarea id="noteNumberInput" placeholder="Note number"></textarea>
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);
});