JSFiddle - React, Tailwind, and code Playground
HTML
INSTRUCTIONS
<ul>
<li>Type letters ONLY in Field 1</li>
<li>Tab to next field; notice the alert which is correct.</li>
<li>Set cursor back to Field 1 and type, but include a digit.</li>
<li>Tab to next field; notice NO ALERT which is wrong.</li>
</ul>
Field 1: <input id="field1" class="letters-only" type="text" /><br />
Field 2: <input id="field2" class="letters-only" type="text" /><br />
CSS
ul { margin-left: 1em; }
li { margin-left: 1em; list-style-type: disc; }
JavaScript
function notSpecialKey(key) {
return (key != 9 && // Tab
key != 13 && // Enter
key != 16 && // Shift
key != 17 && // Ctrl
key != 37 && // Left Arrow
key != 39); // Right Arrow
}
function removeNonLetters(strInput) {
return strInput.replace(/[^A-Za-z]/g, '');
}
document.getElementById("field1").onkeyup = function(){
if (notSpecialKey(event.keyCode)) {
var letters = removeNonLetters(this.value);
this.value = letters;
}
};
document.getElementById("field1").onchange = function(){
alert('changed');
};