0

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.

Paramjeet
  • 316
  • 1
  • 5
  • 18

4 Answers4

2
$('#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.

2

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.

Andrei Todorut
  • 4,260
  • 2
  • 17
  • 28
0

Worked for me

$("#firstname").keyup(function(){
  var text=$(this).val();
  $(this).val(text.replace(/[^(a-zA-Z)]/g,''));
});
Paramjeet
  • 316
  • 1
  • 5
  • 18
0

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/

Naveen P
  • 67
  • 6