Reputation: 27087
I am trying to create a credit validation form. The input field no matter what should always be a maximum of 19 digits and have 4 numeric digits separated by a dash. So far I can do it whilst typing but pasting does not work, neither does editing a few numbers, the form does not update.
I do not want to use any plugins and my client only uses MasterCard and Visa that is why they have asked for 19 digits.
So far, I have also tried to put my code in a loop but the loop is still not working on copy and paste and other scenarios
var cc = $('#cc-card');
// start loop
setInterval(function() {
jQuery(cc).on('propertychange click blur change change keyup keydown paste', function() {
var cctlength = jQuery(this).val().length;
// output should always be 0000-0000-0000-0000
switch (cctlength) {
case 4:
var cctVal = jQuery(this).val();
var cctNewVal = cctVal + '-';
jQuery(this).val(cctNewVal);
break;
case 9:
var cctVal = jQuery(this).val();
var cctNewVal = cctVal + '-';
jQuery(this).val(cctNewVal);
break;
case 14:
var cctVal = jQuery(this).val();
var cctNewVal = cctVal + '-';
jQuery(this).val(cctNewVal);
break;
default:
break;
}
});
// end loop
}, 100);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="cc-card" type="text" maxlength="19" placeholder="•••• •••• •••• ••••">
Upvotes: 2
Views: 786
Reputation: 35491
Firstly, you don't need to use setInterval
, you can just update whenever the input value changed (using the input event).
Secondly, how about anytime a user adds a value, you separate it into chunks of 4 and insert -
in between?
Finally, every time you read a value you can strip all non-numeric characters which will remove added -
as well as any other character the user might have added.
Note: You must also reset the cursor position in case the user edited a digit before the end of the string because updating a value will automatically move the cursor to the end.
const cc = $('#cc-card');
function chunksOf(string, size) {
var i, j, arr = [];
for (i = 0, j = string.length; i < j; i += size) {
arr.push(string.substring(i, i + size));
}
return arr;
}
cc.on('input', function() {
const elem = cc.get(0); // store DOM element ref
const cursorPosition = elem.selectionEnd; // remember cursor position
const value = cc.val().replace(/\D/g, ''); // strip non-numeric chars
const numberChunks = chunksOf(value, 4); // split into 4-digit chunks
const newValue = numberChunks.join('-'); // combine 4-digit chunks into a single string
cc.val(newValue); // update new value
elem.selectionStart = elem.selectionEnd = cursorPosition + 1; // reset cursor position since the value changed
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h3>Enter Credit Card:</h3>
<input id="cc-card" type="text" maxlength="19" placeholder="•••• •••• •••• ••••">
Upvotes: 3