我不确定这是否可行(看起来好像不行),但我正在尝试找到一种方法,在HTML输入标签的onKeyDown或onKeyPress事件中检测即将产生的值。
使用这些事件对我很重要。我不能只使用onKeyUp,因为那时输入框已经发生了变化。我想防止它在第一时间发生。我也尝试将按下的键字符添加到字符串末尾,但那并不能解决你在输入字段开头输入字符的情况。
有什么想法吗?我已经寻找了一段时间,似乎不可能,但我想问问。
我不确定这是否可行(看起来好像不行),但我正在尝试找到一种方法,在HTML输入标签的onKeyDown或onKeyPress事件中检测即将产生的值。
使用这些事件对我很重要。我不能只使用onKeyUp,因为那时输入框已经发生了变化。我想防止它在第一时间发生。我也尝试将按下的键字符添加到字符串末尾,但那并不能解决你在输入字段开头输入字符的情况。
有什么想法吗?我已经寻找了一段时间,似乎不可能,但我想问问。
我这里有两个版本,一个是用jQuery实现的,另一个只使用JavaScript。
$("#inputJQuery").on("keydown", function(ev){
console.log("jQuery value:", $(this).val()); // this is the value before the key is added
console.log("jQuery selectionStart:", this.selectionStart); // the position where the character will be inserted
console.log("jQuery selectionEnd:", this.selectionEnd); // if has a selection this value will be different than the previous
})
document.querySelector("#inputVanilla").onkeydown = function(ev){
console.log("VANILLA value:", this.value); // this is the value before the key is added
console.log("VANILLA selectionStart:", this.selectionStart); // the position where the character will be inserted
console.log("VANILLA selectionEnd:", this.selectionEnd); // if has a selection this value will be different than the previous
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<input id="inputJQuery" type="text"/>
<input id="inputVanilla" type="text"/>
只需在按键事件中检查value
的length
即可。这也适用于删除字符。
您还可以通过条件语句来检查此项,如果超过一定数量的字符,则返回false
以防止用户输入。请注意,您可能需要检查backspace和delete键(分别是keyCodes 8
和46
),以便在达到最大长度后能够删除键。
var input = document.getElementById('input');
input.onkeydown = function(e) {
console.log(input.value.length);
if (input.value.length == 10) {
if (e.keyCode === 8 || e.keyCode === 46) {
return true;
} else {
return false;
}
}
}
<input id="input">
input.value
本身,比如 if (input.value == 1100) { return false; }
,不过这只会在他们实际输入后才进行检查。话虽如此,你真的不应该阻止他们输入任何东西,而是在表单提交(或逻辑处理)后验证输入。 - Obsidian Ageblur()
事件,如果输入无法接受,则添加内联错误消息。然后用户就知道他们需要更改它。不过,仅进行前端验证是绝对不够的,你应该始终在后端进行验证(不要忘记在提交表单后可以操作数据)。 - Obsidian Age