当value为number时显示警报



我需要显示当用户在输入字段中输入数字时的警告框

<input type="text" class="only-text">
if (document.querySelector('.only-text').value === '') {alert('no numbers are allowed!')};

我会使用beforeinput事件,这样你就可以检查在DOM中绘制之前插入的值,如果它不好,你可以阻止它被绘制。

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">

相关内容

最新更新