How do I remove all spaces on paste using jQuery or JavaScript at once?
When the user inserts some text into the field, I want to be able to instantly remove all spaces.
<input type="text" class="white-space-is-dead" value="dor on" />
$('.white-space-is-dead').change(function() {
$(this).val($(this).val().replace(/\s/g,""));
});
This code from another example works. But it doesn't update until the user clicks on something other than the text field. I am using MVC with jQuery / JavaScript.
+3
source to share
2 answers
Toggle the event change
for input
, which will fire whenever something is entered into the field, even if text is inserted.
$('.white-space-is-dead').on('input', function() {
$(this).val($(this).val().replace(/\s/g,""));
});
Take a look at jQuery Events for a better understanding of what options you have.
Edit: Updated the answer based on the OP's comment and what I found on this answer .
+3
source to share
The regex didn't do what you wanted. This works, but doesn't work until the text 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" />
+1
source to share