简体   繁体   中英

Key-Press event listener when checking textarea input in Javascript

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.");
    }
}

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM