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

how-to-add-letter-spacing-after-every-4-digits-of-credit-card-in-html-using-javascript

It is always a good practise to mask input text boxes for standardizing data in various formats. In this article we will see how to add letter-spacing after every 4 digits of credit card in HTML using JavaScript

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’s keyup function.

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 credit card input field.

1. HTML

Lets create an input field with length as 20 characters. The 16 digits for card number while 4 are for spaces.

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

2. JavaScript

Now, lets write a JavaScript code that will format and add letter-spacing after every 4 digits of credit card runtime.

At the bottom of your file (before the closing of body tag) add the following snippet:

<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, ''); 
    
    // iterate to letter-spacing after every 4 digits   
    for(var i = 0; i < val.length; i++) {             
      if(i%4 == 0 && i > 0) newval = newval.concat(' ');             
      newval = newval.concat(val[i]);         
    }        

    // format in same input field 
    $(this).val(newval);     
   });   
</script>

You can change the id of your element as per your dom.

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.

Related Posts