Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strip white spaces on input

Tags:

jquery

I have a field that does not need any white spaces. I need to remove any as they are entered. Here's what I'm trying... no luck so far

$('#noSpacesField').click(function() {
    $(this).val().replace(/ /g,'');
});
like image 544
santa Avatar asked Aug 17 '12 17:08

santa


3 Answers

Use jQuery trim to remove leading and trailing white space

$.trim(" test case "); // 'test case'

To remove all whitespace...

" test   ing  ".replace(/\s+/g, ''); // 'testing'

To remove whitespace as it is entered...

$(function(){
  $('#noSpacesField').bind('input', function(){
    $(this).val(function(_, v){
      return v.replace(/\s+/g, '');
    });
  });
});

Live Example

like image 74
Kyle Avatar answered Oct 02 '22 12:10

Kyle


$('#noSpacesField').keyup(function() {
  $(this).val($(this).val().replace(/ +?/g, ''));
});

This will remove spaces as you type, and will also remove the tab char.

like image 33
Bot Avatar answered Oct 02 '22 11:10

Bot


If you only wanna put numbers, try this! :D

$("#id").keyUp(function(){
   if(isNaN($(this).val())) {
     $(this).val(0);
   }
   $(this).val($(this).val().replace(/ +?/g, ''));
})
like image 1
Alfiian Avatar answered Oct 02 '22 12:10

Alfiian