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.");
    }
}
7
  • thanks for what? whats the problem, whats not working? Commented Dec 12, 2014 at 15:12
  • so whats the problem Commented Dec 12, 2014 at 15:12
  • 1
    So you catch keypresses. BUT what if they paste? Commented Dec 12, 2014 at 15:13
  • An entire textarea of just digits? Unusual... Commented Dec 12, 2014 at 15:14
  • I want to prevent from adding the charcter in case of not a number character. Commented Dec 12, 2014 at 15:18

1 Answer 1

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
}
Sign up to request clarification or add additional context in comments.

3 Comments

@T.J.Crowder - Good to know.. I often forget about older browsers :\ - updating answer.
how do i block the character from being inserted to the textarea value in case of not a number?
@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 and you can always rely on event.preventDefault();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.