Disable spaces in Input, AND allow back arrow?

Solution 1:

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/

Solution 2:

This seems to work for me:

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

Solution 3:

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

Solution 4:

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 keyCode of 32 (a space) calls the replace function. This will allow the other keypress events to get through. Depending on comparability in IE, you may need to check whether e exists, use e.which, or perhaps use the global window.event object. There are many question on here that cover such topics though.

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