0

I want to check two conditions for every button press on the keyboard inside a textarea:

1) If it's a number then add it to the text area.

2) If it's anything else push an alert to the user.

The textarea tag in the html is:

<textarea id="input" placeholder="EnterInput"></textarea>

What I wrote inside the JS file is:

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.");
    }
}
Nathan Arthur
  • 8,287
  • 7
  • 55
  • 80
itzikos
  • 375
  • 1
  • 5
  • 13

1 Answers1

4

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:

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

function checkInput(event) {
    var keyCode = event.hasOwnProperty('which') ? event.which : event.keyCode;
    //Now check
}
tymeJV
  • 103,943
  • 14
  • 161
  • 157
  • @T.J.Crowder - Good to know.. I often forget about older browsers :\ - updating answer. – tymeJV Dec 12 '14 at 15:17
  • how do i block the character from being inserted to the textarea value in case of not a number? – itzikos Dec 12 '14 at 15:17
  • 1
    @user3126715: On modern browsers: `event.preventDefault();` On older IE: `event.returnValue = false;`. So `if (event.preventDefault) { event.preventDefault(); } else { event.returnValue = false; }` Or use `hookEvent` from [this answer](http://stackoverflow.com/a/23799448/157247) and you can always rely on `event.preventDefault();` – T.J. Crowder Dec 12 '14 at 15:20