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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14236873/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 16:07:27  来源:igfitidea点击:

Disable spaces in Input, AND allow back arrow?

javascriptjqueryhtmlinput

提问by jakeforaker

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/

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

回答by VisioN

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

您可以添加keydown处理程序并阻止空格键的默认操作(即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/

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

回答by Lightness Races in Orbit

It doesn't "disable" the back arrow — your code keeps replacing all the text outright, whenever you press a key, and every time that happens the caret position is lost.

它不会“禁用”后退箭头——每当您按下一个键时,您的代码都会不断替换所有文本,并且每次发生插入符号位置都会丢失。

Simply don't do that.

不要那样做。

Use a better mechanism for banning spaces, such as returning falsefrom an onkeydown handler when the key pressed is space:

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

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

This way, your textbox is prohibited from receiving the spaces in the first place and you don't need to replace any text. The caret will thus remain unaffected.

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



Update

更新

@VisioN's adapted codewill also add this space-banning support to copy-paste operations, whilst still avoiding text-replacement-on-keyuphandlers that affect your textbox value whilst your caret is still active within it.

@VisioN的改编代码还将将此空间禁止支持添加到复制粘贴操作,同时仍然避免keyup影响您的文本框值的text-replacement-on-处理程序,而您的插入符号仍在其中。

So here's the final code:

所以这是最终的代码:

$(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.
    });?????
});

回答by Chase

Try checking for the proper key code in your function:

尝试在您的函数中检查正确的键代码:

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

That way only the keyCodeof 32(a space) calls the replace function. This will allow the other keypressevents to get through. Depending on comparability in IE, you may need to check whether eexists, use e.which, or perhaps use the global window.event object. There are many question on here that cover such topics though.

这样只有keyCodeof 32(a space) 调用替换函数。这将允许其他keypress事件通过。根据 IE 中的可比性,您可能需要检查是否e存在、使用e.which或使用全局 window.event 对象。不过,这里有很多问题涵盖了这些主题。

If you're unsure about a certain keyCodetry this helpful site.

如果您对某个不确定,请keyCode尝试这个有用的网站

回答by Dustin Spengler

This seems to work for me:

这似乎对我有用:

<input type="text" onkeypress="return event.charCode != 32">