问题描述
我有一个案例,当我阻止用户输入空格作为输入字段的第一个字符。
我在这里演示了一个演示:
只有当您第一次打空格键时才有效。当您开始输入其他字符并在输入(ctrl + a)中选择整个文本,然后按空格键时,它会在输入字段的开头添加空格。
所以,如果第一个字符将是空格,如何检查是否按键,返回false并不允许它将空格键入第一个字符?
您可以通过检查键是否为空格
和选择开始
为0以下:
$(function(){
$('body')。on('keydown' #test',function(e){
console.log(this.value);
if(e.which === 32& amp; e.target.selectionStart === 0){
return false;
}
});
});
Good morning everybody!
I have a case, when I should prevent users to entering space as a first character on input field.
I have a demo here: http://jsbin.com/foyetolo/2/edit
It works only when you hit spacebar for first time. When you start typing other characters and select whole text in input (ctrl+a) and then hit the space bar it adds the space in the beginning of input field.
So, how to check if on keypress/keydown if the first character will be a space, return false and not allow it to type the space as a first character?
You can do this by checking if key is space
and selection start
is 0 as below:
$(function() {
$('body').on('keydown', '#test', function(e) {
console.log(this.value);
if (e.which === 32 && e.target.selectionStart === 0) {
return false;
}
});
});
这篇关于如何禁用/删除输入字段的第一个空格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!