mrchad mrchad - 1 month ago 30
Javascript Question

Insert dash after every 4th character in input

I want insert a dash after every 4th character in input. I have a credit card input box. When a user is typing and reaches each 4th character, then jQuery will insert a hyphen (

-
).

For example:
1234-5678-1234-1231


UPDATE: I'm trying some codes and i think i'm so close to correct code but i have some problems. Here is my code sample;

$('.creditCardText').keyup(function() {

var cardValue = $('.creditCardText').val(),
cardLength = cardValue.length;

if ( cardLength < 5 ) {
if ( cardLength % 4 == 0 ) {
console.log('4 lük geldi');
cardValue += "-";
$('.creditCardText').val(cardValue);
}
} else {
if ( cardLength % 5 == 0 ) {
console.log('5 lük geldi');
cardValue += "-";
$('.creditCardText').val(cardValue);

}
}

});

Answer

This jquery extension will insert a space every four characters: https://github.com/stripe/jquery.payment