5

I've a textbox of order id(7 digits), which in normal cases you copy paste from email to the textbox, many times you accidently copy one or two white spaces which causing annoying validation error.

I want jquery code in my Layout\MasterPage that does't allow writing white spaces and when copy paste (with keyboard or mouse) numbers with white spaces removes the spaces and keeps the numbers only.

The above should happen only on textboxes with class white-space-is-dead

gdoron
  • 147,333
  • 58
  • 291
  • 367

2 Answers2

7

Do

$('.white-space-is-dead').change(function() {   
    $(this).val($(this).val().replace(/\s/g,""));
});

Updated copy of your fiddle.

Note that \s may be more than you like. If so, use a literal white space instead

.replace(/ /g,""));

P.Brian.Mackey
  • 43,228
  • 68
  • 238
  • 348
  • @gdoron, that's for testing...sorry I meant to take that out. I updated the answer. – P.Brian.Mackey Nov 29 '11 at 21:17
  • it's better to pass a callback function to the val method in that case, like so: `$( this ).val(function( index, oldValue ) { return oldValue.replace( /\s/g, "" ); });` it avoid 2 calls to `$(this)` and `.val()` – pomeh Nov 29 '11 at 21:25
  • 1
    It writes out to the error console in firefox. You can see it with FireBug. Its an easy way to see variable values when you are debugging. Its usage is simple `console.log(variableName)`. – P.Brian.Mackey Nov 29 '11 at 21:25
1
$('.white-space-is-dead').change(function() {   
    $(this).val($(this).val().replace(/\s/g,""));
});

This will remove all the white spaces using a regular expression.

gillyb
  • 8,760
  • 8
  • 53
  • 80
  • this will replace all white space in the string, including all space characters, ne lines, tabs, etc. – u.k Nov 29 '11 at 21:05
  • Can you please be kind and make jsFiddle? I did't succeeded to make it work. see my jsFiddle http://jsfiddle.net/U3CRg/22/ – gdoron Nov 29 '11 at 21:13
  • I updated the code in my comment... (hope this is good enough) :) – gillyb Nov 29 '11 at 21:16