Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Space out every 4 numbers

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?

like image 378
ngplayground Avatar asked Jun 12 '12 15:06

ngplayground


People also ask

How do I add a space between numbers in Javascript?

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.

How do you put a space between strings in Javascript?

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.


1 Answers

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:

  • on blur (i.e. when leaving the input): split every 4 chars;
  • on focus (i.e. when editing the input): remove the previously added whitespaces.
like image 78
sp00m Avatar answered Sep 21 '22 10:09

sp00m