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

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

问题描述

我正在尝试禁用用户名文本字段中的空格,但是我的代码也禁用了使用后退箭头.有什么办法也允许后退箭头吗?

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);
    });

小提琴:http://jsfiddle.net/EJFbt/

推荐答案

您可以添加 keydown 处理程序并阻止空格键(即 32)的默认操作:

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, "");
  }
});

演示: http://jsfiddle.net/EJFbt/1/

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

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