4 回答

TA贡献1833条经验 获得超4个赞
function onlyAlphabet(inputVal) {
var patt=/^[a-zA-Z]+$/;
if (patt.test(inputVal)) {
document.getElementById('text').value = inputVal;
} else {
var txt = inputVal.slice(0, -1);
document.getElementById('text').value = txt;
}
}
<input id="text" type="text" oninput="onlyAlphabet(value)">

TA贡献1982条经验 获得超2个赞
另一种方法是使用 keydown 事件(不推荐使用 keypress)。
function inputPattern(e) {
var test = e.key.search(/[a-zA-Z]/);
if(test < 0) e.preventDefault();
}
<input type="text" onkeydown='inputPattern(event)'>

TA贡献1818条经验 获得超3个赞
另一种方法是使用 keydown 事件(不推荐使用 keypress)。
function inputPattern(e) {
var test = e.key.search(/[a-zA-Z]/);
if(test < 0) e.preventDefault();
}
<input type="text" onkeydown='inputPattern(event)'>

TA贡献1829条经验 获得超7个赞
我不知道如何检查是否按下了某个键,但如果它只是一个输入,那么您可以这样做吗?
<input type="text" pattern="[A-Za-z]" onkeypress="someFunction()">
添加回答
举报