I have an input box which is limited to 16 Numbers. What I'd like to do for aesthetics would be to place a gap per 4 numbers.
EG. When a person enters
1234567891234567
It should look like this
1234 5678 9123 4567
How would this be possible on Key Up in JQuery?
To add a space between characters of a string, call the split() method on the string to get a character array, then call the join() method on the array to join the characters with a space separator.
To add two strings we need a '+' operator to create some space between the strings, but when the first string itself has a space with in it, there is no need to assign space explicitly.
Here is another solution:
$(function() {
$('#my-input')
.blur(function() {
var value = $(this).val();
value = value.match(/.{1,4}/g).join(" ");
$(this).val(value);
})
.focus(function() {
var value = $(this).val();
value = value.replace(/\s/g, '');
$(this).val(value);
});
});
You can have a look at that working jsFiddle.
I added a focus
event to make it more user-friendly. To sum up:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With