禁用输入中的空格,并允许后退箭头?

jak*_*ker 15 html javascript jquery input

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

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

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

Vis*_*ioN 53

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

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

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

  • 好的; 那讲得通.如果在答案中给出那种解释,那将是很好的. (5认同)
  • 跨浏览器文本粘贴需要@LightnessRacesinOrbit`change`. (2认同)

Dus*_*ler 14

这似乎对我有用:

<input type="text" onkeypress="return event.charCode != 32">
Run Code Online (Sandbox Code Playgroud)


Lig*_*ica 5

它不会"禁用"后退箭头 - 只要您按下某个键,您的代码就会一直替换所有文本,并且每次发生这种情况时,插入符号位置都会丢失.

根本不要那样做.

使用更好的机制来禁止空格,例如当按下的键是从onkeydown处理程序返回falsespace:

$(function() {
    $("input#Username").on("keydown", function (e) {
        return e.which !== 32;
    });?????
});
Run Code Online (Sandbox Code Playgroud)

这样,您的文本框首先被禁止接收空格,您不需要替换任何文本.因此,插入符号将不受影响.


更新

@VisioN的改编代码也将为复制粘贴操作添加这种禁止空格的支持,同时仍然避免keyup在您的插入符号仍处于活动状态时影响文本框值的文本替换处理程序.

所以这是最终的代码:

$(function() {

    // "Ban" spaces in username field
    $("input#Username").on({

       // When a new character was typed in
       keydown: function(e) {

          // 32 - ASCII for Space;
          // `return false` cancels the keypress
          if (e.which === 32)
             return false;
       },

       // When spaces managed to "sneak in" via copy/paste
       change: function() {
          // Regex-remove all spaces in the final value
          this.value = this.value.replace(/\s/g, "");
       }

       // Notice: value replacement only in events
       //  that already involve the textbox losing
       //  losing focus, else caret position gets
       //  mangled.
    });?????
});
Run Code Online (Sandbox Code Playgroud)