在输入中禁用空格,并允许后退箭头? [英] Disable spaces in Input, AND allow back arrow?

查看:146
本文介绍了在输入中禁用空格,并允许后退箭头?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在用户名文本字段中禁用空格,但是我的代码也禁用了后退箭头。任何方式允许后退箭头也可以吗?

  $(function(){
var txt = $(input #UserName);
var func = function(){
txt.val(txt.val()。replace(/ \s / g,''));
}
txt.keyup(func).blur(func);
});

小提琴: c> keydown 处理程序,并阻止空格键的默认操作(即 32 ):

<$ (
keydown:function(e){
if(e.which === 32)$ b $($ input $#$> $(input#UserName b返回false;
},
change:function(){
this.value = this.value.replace(/ \s / g,);
}
});

DEMO: http://jsfiddle.net/EJFbt/1/

I am trying to disable spaces in the Username text field, however my code disables using the back arrow too. Any way to allow the back arrow also?

    $(function() {
         var txt = $("input#UserName");
         var func = function() {
                      txt.val(txt.val().replace(/\s/g, ''));
                   }
         txt.keyup(func).blur(func);
    });

fiddle: http://jsfiddle.net/EJFbt/

解决方案

You may add keydown handler and prevent default action for space key (i.e. 32):

$("input#UserName").on({
  keydown: function(e) {
    if (e.which === 32)
      return false;
  },
  change: function() {
    this.value = this.value.replace(/\s/g, "");
  }
});

DEMO: http://jsfiddle.net/EJFbt/1/

这篇关于在输入中禁用空格,并允许后退箭头?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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