如何禁用/删除输入字段的第一个空格? [英] How to disable/remove only first space on input field?

查看:177
本文介绍了如何禁用/删除输入字段的第一个空格?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个案例,当我阻止用户输入空格作为输入字段的第一个字符。



我在这里演示了一个演示: http://jsbin.com/foyetolo/2 / edit



只有当您第一次打空格键时才有效。当您开始输入其他字符并在输入(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;
    }  
  });
});

Demo Link

这篇关于如何禁用/删除输入字段的第一个空格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆