Reputation: 2567
Until now I have used the method below to prevent multiple spaces in my text fields. This works fine unless letters are inserted in the middle of strings. In this JSfiddle demo, you can see that if you click the cursor between 'a' and 'c' and type 'b', it adds the new letter to the end of the string spelling 'acb' not 'abc'. I was hoping someone might know an alternative to string replace, which might solve this issue. Thanks.
$('#tBox').bind('DOMAttrModified textInput input change paste',function(){
var sspace = $(this).val().replace(/ +/g, ' ');
$(this).val(sspace);
});
<input type = "text" id = "tBox" />
Upvotes: 0
Views: 961
Reputation: 11922
What's happening is that your events are catching the change before the 'b' has been inserted into the text field. i.e. With your abc/acb example, you have the sequence of events:
1) user presses 'b'
2) event handlers run with the value of the input still given as 'ac'.
3) the handlers set the value of the input to 'ac', moving the cursor to the end of the input
4) browser inserts 'b' character at the cursor position, which is now at the end of the field
Only thing I can think to do is to only do (3) when needed i.e.:
$('#tBox').bind('DOMAttrModified textInput input change paste',function(){
var sspace = this.value.replace(/ +/g, ' ');
if (this.value !== sspace) {
this.value = sspace;
}
});
This still moves the cursor to the end when inputting multiple spaces, but it's an improvement.
Also, I got rid of the unneeded use of jQuery for $(this).val().
Upvotes: 1
Reputation: 1018
The problem is because you update the value with the change event, which happens before the content gets updated, so by resetting the input value to it's newest value 'ac', the cursor position itself at the end of the text, then captures the 'b', so you get 'acb'.
I updated your jsfiddle to use the keyup event instead of the change event and validating that the text has changed before updating the input content
$('#tBox').bind('DOMAttrModified textInput input keyup paste',function(){
var sspace = $(this).val().replace(/ +/g, ' ');
if ($(this).val() != sspace)
$(this).val(sspace);
});
Upvotes: 1