HTMLJavaScript

How to add letter-spacing after every 4 digits of credit card in HTML using JavaScript

2
1.7k
2019 / 10 / 26

It is always a good practise to mask input text boxes for standardizing data in various formats.

One of the hot topics in masking input text boxes is for masking credit card numbers. The credit card, master card, visa card and union card etc. have their format for having space after every 4 digits. We can achieve a space after every 4 digits using JavaScript.

Lets first see how credit card number looks without masking:

How to add letter-spacing after every 4 digits of credit card in HTML using JavaScript - without masking

Here you will notice that it is a bit difficult to read such 16 digits without masking. With the following simple JavaScript snippet, we can add masking to our input.

HTML

<input type="text" size="20" autocomplete="off" class="form-control" id="number" required />

JavaScript

<script type="text/javascript">
    // enable spacing for credit card number
    $('#number').on('keyup', function(e){
        var val = $(this).val();
        var newval = '';
        val = val.replace(/\s/g, '');
        for(var i = 0; i < val.length; i++) {
            if(i%4 == 0 && i > 0) newval = newval.concat(' ');
            newval = newval.concat(val[i]);
        }
        $(this).val(newval);
    });
  </script>

After applying the above script, we will get masking as below:

How to add letter-spacing after every 4 digits of credit card in HTML using JavaScript - with masking

Now, you will notice that the numbers are easy to read and in a format which a payment card normally has.

Hi, I am a full-stack web developer with 5+ years of experience in working with different web technologies. Do you want to ask something? just send me a message through the contact form. Please visit my portfolio at hamzamehmood.com. Thanks