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/
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 isspace
: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:
Try checking for the proper key code in your function:
That way only the
keyCode
of32
(a space) calls the replace function. This will allow the otherkeypress
events to get through. Depending on comparability in IE, you may need to check whethere
exists, usee.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.You may add
keydown
handler and prevent default action for space key (i.e.32
):DEMO: http://jsfiddle.net/EJFbt/1/