Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disable spaces in Input, AND allow back arrow?

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/

like image 459
jakeforaker Avatar asked Jan 09 '13 13:01

jakeforaker


People also ask

How do you restrict space in HTML?

you can use the onkeypress event of the input tag to react to keypresses. While appending text at the end it would be easy: just cancel the keypress event in case there is already a space at the end of the text field, but since you may also be editing inside an existing text string you better use the onkeyup event.


4 Answers

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/

like image 72
VisioN Avatar answered Oct 30 '22 17:10

VisioN


This seems to work for me:

<input type="text" onkeypress="return event.charCode != 32">
like image 20
Dustin Spengler Avatar answered Oct 30 '22 18:10

Dustin Spengler


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.
    });​​​​​
});
like image 31
Lightness Races in Orbit Avatar answered Oct 30 '22 17:10

Lightness Races in Orbit


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.

like image 41
Chase Avatar answered Oct 30 '22 17:10

Chase