To mask a credit card number during input using jQuery, you can use a combination of jQuery event handlers and string manipulation. Here's a simple example of how you can achieve this:


<label for="credit-card">Credit Card Number:</label> <input type="text" id="credit-card" maxlength="19" placeholder="xxxx xxxx xxxx xxxx">


<script src=""></script> <script> $(document).ready(function() { $('#credit-card').on('input', function() { // Remove any non-numeric characters var creditCardNumber = $(this).val().replace(/\D/g, ''); // Create a masked version of the credit card number var maskedNumber = maskCreditCardNumber(creditCardNumber); // Update the input value with the masked number $(this).val(maskedNumber); }); }); function maskCreditCardNumber(number) { // Keep the last 4 digits unmasked var masked = number.slice(0, -4).replace(/./g, 'x') + number.slice(-4); // Add spaces after every 4 digits for better readability masked = masked.replace(/(.{4})/g, '$1 '); return masked; } </script>

In this example, we have an input field for the credit card number with a maxlength of 19 to accommodate the space characters added by the mask. We also use the placeholder attribute to display a format hint for the credit card number (e.g., "xxxx xxxx xxxx xxxx").

The jQuery code attaches an input event handler to the credit card input field. Whenever the user inputs or changes a character, the handler is triggered. Inside the event handler, we remove any non-numeric characters from the input using a regular expression. Then, we call the maskCreditCardNumber function to create a masked version of the credit card number. The function replaces all characters except the last 4 digits with 'x' and adds spaces after every 4 digits for better readability.

Finally, the input field is updated with the masked credit card number using the val method.

With this approach, the credit card number will be displayed in a masked format (e.g., "xxxx xxxx xxxx 1234") as the user types it in.

Have questions or queries?
Get in Touch