Disable Spacebar in a textfield with jQuery

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" />

Share the love

Leave a Comment

Please keep in mind that comments are moderated and rel="nofollow" is in use. You can use [code][/code] if you want to write codes. Don't spam us :) Thanks!

Advertisement