Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent number input on keydown?

I want to prevent number input on keydown event on textfield and run custom handler function. Here are the issues

  • e.target.value is useless since the key value is not projected into the target value yet
  • e.keyCode for number depends on keyboard type, language layout, Fn or Shift key
  • String.fromCharCode(e.keyCode) is not reliable, at least on my keyboard (Czech qwerty)
  • w3 specification says e.keyCode is a legacy attribute and suggests e.char instead, but it is not implemented in browsers yet

So how to catch the number input before it appears in the textfield?

like image 348
Jan Turoň Avatar asked Mar 31 '13 09:03

Jan Turoň


People also ask

How do you restrict e input type number in react?

To prevent e and dot in an input type number with React, we can validate the input value in the onChange prop function. const C = () => { //... const [val, setVal] = useState(""); return ( <div className="App"> <input type="text" value={val} onChange={(e) => setVal(e. target.

How do you disable the Enter key of an input textbox?

Disabling enter key for the formaddEventListener('keypress', function (e) { if (e. keyCode === 13 || e. which === 13) { e. preventDefault(); return false; } });


1 Answers

Use the keypress event instead. It's the only key event which will give you information about the character that was typed, via the which property in most browsers and (confusingly) the keyCode property in IE. Using that, you can conditionally suppress the keypress event based on the character typed. However, this will not help you prevent the user from pasting or dragging in text containing numeric characters, so you will still need some kind of extra validation.

My favourite reference for JavaScript key events: http://unixpapa.com/js/key.html

textBox.onkeypress = function(e) {
    e = e || window.event;
    var charCode = (typeof e.which == "undefined") ? e.keyCode : e.which;
    var charStr = String.fromCharCode(charCode);
    if (/\d/.test(charStr)) {
        return false;
    }
};
like image 56
Tim Down Avatar answered Nov 02 '22 20:11

Tim Down