2

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);

});
Xander
  • 991
  • 1
  • 13
  • 32
  • How is that different from [How to limit the textarea to only hold numbers?](http://stackoverflow.com/questions/22571923/how-to-limit-the-textarea-to-only-hold-numbers) – Mistalis Apr 24 '17 at 15:12
  • check out this http://stackoverflow.com/questions/8936018/limit-input-to-numbers-and-on-input-field – Aldin Juko Apr 24 '17 at 15:12

1 Answers1

1

Your function needs the key parameter:

function validate(key) {
....
Simon
  • 1,081
  • 9
  • 14