I have following code :-
/*****html*********/
<input type="text" id="firstname">
/******jquery********/
$(document).ready(function(){
$("#firstname").keyup(function(){
var text=$(this).val();
$(this).val(text.replace(/[^\s((a-zA-Z))]/g,''));
});
});
I don't want any whitespace in my input box.Tried above code but not working. Something wrong in my code. Please help.
4 Answers 4
$('#firstname').keypress(function( e ) {
if(e.which === 32)
return false;
});
You can prevent key press if white space. So that no one can type it.
3 Comments
Your regex is wrong. Please check this https://jsfiddle.net/w1uqqsc3/
$(this).val(text.replace(/[\s((0-9))]/g,''));
Use this app for regex http://regexr.com/
There you can find references about regex.
Comments
Worked for me
$("#firstname").keyup(function(){
var text=$(this).val();
$(this).val(text.replace(/[^(a-zA-Z)]/g,''));
});
Comments
If you try to do replacement during keyup event, you might face cursor jump issues while trying to edit the text.
I would prefer to allow them typing whatever they want and clean-up the text during change event as below (This would work perfectly for copy-paste scenario too):
$(document).ready(function(){
$("#firstname").change(function(){
var text=$(this).val();
$(this).val(text.replace(/\s/g,''));
});
});
JS Fiddle: https://jsfiddle.net/pnaveen/w1uqqsc3/2/