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.

2
  • 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. Commented May 15, 2015 at 1:13
  • 2
    That was a typo sorry. Commented May 15, 2015 at 1:14

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

7 Comments

This works if the user keeps typing. But I want it to happen during the paste action or right after.
that seems to do the job but I am wondering now if older browsers will support the paste event.
As long as they support your jQuery version, I believe you won't have any problems with that.
@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.
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.
|
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" />

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.