'show alert when value is number
I need to show the alert box when the user typed the number in the input field
<input type="text" class="only-text">
if (document.querySelector('.only-text').value === '') {alert('no numbers are allowed!')};
Solution 1:[1]
I'd use the beforeinput
event, this way you can check the value inserted before it is painted in the DOM, and if it's not good you can prevent it from being painted.
function isBeforeInputEventAvailable() {
return window.InputEvent && typeof InputEvent.prototype.getTargetRanges === "function";
}
if (isBeforeInputEventAvailable()) onlyText.addEventListener("beforeinput", e => {
if (/[\d]+/.test(e.data)) {
alert('no numbers are allowed!')
e.preventDefault()
};
})
<input type="text" id="onlyText">
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Cesare Polonara |