Disable spaces in Input, AND allow back arrow?

后端 未结 4 959
感动是毒
感动是毒 2020-11-30 09:02

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?

    $(func         


        
4条回答
  •  甜味超标
    2020-11-30 09:43

    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 false from an onkeydown handler when the key pressed is space:

    $(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 code will also add this space-banning support to copy-paste operations, whilst still avoiding text-replacement-on-keyup handlers that affect your textbox value whilst your caret is still active within it.

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

提交回复
热议问题