6

I have the following jQuery shell which works:

  $('.jq_noSpaces').on('change', function(){
    alert('you changed the value in the box');
  });

My form attributes are id="username" name="username"

How do I use the following jQuery replace function to automatically change remove the spaces from the input field?

str.replace(/\s+/g, '');

Thanks

H. Ferrence
  • 7,906
  • 31
  • 98
  • 161

4 Answers4

12

You can use the syntax:

$(this).val($(this).val().replace(/\s+/g, ''));

Inside the event handler.

Tom Walters
  • 15,366
  • 7
  • 57
  • 74
4

Replace content of your box in event handler

this.value = this.value.replace(/\s+/g, '');
Anoop
  • 23,044
  • 10
  • 62
  • 76
3

No need for jQuery at all...just do this.value = this.value.replace(/s+/g, '');

Travesty3
  • 14,351
  • 6
  • 61
  • 98
0
$('.jq_noSpaces').on('change', function(){
    $(this).val($(this).val().replace(/\s+/g,"")) //thanks @Sushil for the reminder to use the global flag
    alert('you changed the value in the box');
});

or, like the others said, you don't really need jQuery at all. I tend to use it anyway, though. All the really cool coders do.

Phillip Schmidt
  • 8,805
  • 3
  • 43
  • 67