3

When a user pastes some text into a field I want to be able to remove all spaces instantly.

<input type="text" class="white-space-is-dead" value="dor  on" />

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

http://jsfiddle.net/U3CRg/22/

This code from another example works. But doesn't update until a user clicks on something besides the textbox. I am using MVC with jQuery/JavaScript.

mathielo
  • 6,725
  • 7
  • 50
  • 63
Bob
  • 1,065
  • 2
  • 16
  • 36
  • Just want to quick point out java and javascript are two different languages that are completely unrelated. (other then similarity in name). This is javascript. – Philippe May 15 '15 at 01:13
  • 2
    That was a typo sorry. – Bob May 15 '15 at 01:14

2 Answers2

3

Switch the event change for input, which will trigger whenever something is inputted into the field, even if text is being pasted.

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

Take a look at jQuery Events to understand better what options you have.

Edit: updated the answer based on OP's comment and what I found on this answer.

Community
  • 1
  • 1
mathielo
  • 6,725
  • 7
  • 50
  • 63
  • This works if the user keeps typing. But I want it to happen during the paste action or right after. – Bob May 15 '15 at 01:13
  • that seems to do the job but I am wondering now if older browsers will support the paste event. – Bob May 15 '15 at 01:26
  • As long as they support your jQuery version, I believe you won't have any problems with that. – mathielo May 15 '15 at 01:28
  • @Bob also, if it's really **really** important to not have any spaces in the inputted text, you should consider server-side validating and/or replacing spaces. – mathielo May 15 '15 at 01:31
  • I am trying to remove the spaces, blocking the space-bar key works for regular input but when the user pastes in spaces I need a to remove them. Which your answer does cover but I feel as IE8 wont like it.I'm open to suggestions. – Bob May 15 '15 at 01:37
  • So @Bob, have you tested it on IE8 yet? – mathielo May 19 '15 at 12:26
  • actually I went a different direction with the input. Took the text on the form trimmed it and set that to another variable to submit. As for IE8 for some reason I was getting an infinite loop may of been do to other code as well. – Bob Jun 09 '15 at 17:56
1

The regex wasnt doing what you wanted. This works but does not fire until the text input loses focus.

$('.white-space-is-dead').change(function() {   
    $(this).val($(this).val().replace(/ /g,''));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type="text" class="white-space-is-dead" value="dor  on" />
Allen Tellez
  • 1,198
  • 1
  • 10
  • 14