How to remove spaces from input text box

I have the following jQuery shell that works:

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

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

How to use the following jQuery replace function to automatically change the removal of spaces from an input field?

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

thanks

+4
source share
4 answers

You can use the syntax:

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

Inside the event handler.

+11
source

Replace field contents in event handler

 this.value = this.value.replace(/\s+/g, ''); 
+3
source

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

+2
source
 $('.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, as others have said, you don't need jQuery at all. Although I still use it. All really cool coders do.

0
source

All Articles