Back jQuery

Disable Spacebar in a textfield with jQuery

WRITTEN BY ON 16 Jan 2011
25,880 VIEWS • SHARES
3 comments

Alright, a short and useful code snippet for textfield. You can use this code to disable certain keys to be entered into a textfield or textarea by detecting its keycode.

JS - jQuery

This is how you do it, once the keycode of the spacebar is detected, it returns false which disallow the entering of space. If you want to disable some other keys, you can refer to this keycode table:
http://www.foreui.com/articles/Key_Code_Table.htm

Alternatively, you can use alert to display the keycode of the key you've pressed.

$('input.nospace').keydown(function(e) {

        // alert (e.keyCode);

	if (e.keyCode == 32) {
		return false;
	}
});

HTML/XHTML

All you have to do is add a class called "nospace" to the textfield you want to apply with this restriction.

<input type="text" class="nospace" name="mobileno" />
Join the discussion

Comments will be moderated and rel="nofollow" will be added to all links. You can wrap your coding with [code][/code] to make use of built-in syntax highlighter.

3 comments
Virendra 13 years ago
That’s really nice list of snippets. While searching about more, I found a good link which has lots of jquery code snippets.

http://jquerybyexample.blogspot.com/2011/08/mostly-used-and-essential-jquery-code.html
Reply
bnbv vbvbcvbcv 11 years ago
fhf gcghgh dfhgf ggfhfg
Reply
Alex 11 years ago
I came up with the following solution if you're dealing with lots of Ajax loaded forms & don't want to keep track of whether they've had the event applied:

$(window).on('keydown',function(e){
if ($(e.target).hasClass('nospace') && e.keyCode == 32) {
return false;
}
});
Reply