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); } } });
To insert hyphens into a JavaScript string, we can use the JavaScript string's replace method. We call phone. replace with a regex that has 3 capturing groups for capturing 2 groups of 3 digits and the remaining digits respectively. Then we put dashes in between each group with '$1-$2-$3' .
In Windows, use ALT + 0151. To use an em dash on a web page, create it in HTML with "—" or "—." You can also use the Unicode numeric entity of U+2014.
I absolutely love this plugin for automatic formatting: here.
So long as you're already using JQuery, that is.
You could easily force the dashes in with a single line of code, like follows:
$("#credit").mask("9999-9999-9999-9999");
When the user types in the field, the dashes will automatically appear in the right spot, and they will not be able to delete them.
In addition, you can accommodate for different lengths or formats of credit cards with the ?
character in your mask. For example, to accept inputs of 14 and 16 digits, you would do the following:
$("#credit").mask("9999-9999-9999-99?99");
Do keep in mind that this is only a client side validation
Edit: The mask plugin assumes that there is one, or finitely many, correct formats for the field. For example, there are only a few formats that credit card numbers come in. The plugin is there to ensure that your input will only be in one of those formats.
So technically, if you want a dash after every four digits, but for any number of digits, then this plugin is not right for you.
I would suggest you restrict the possible inputs to be reasonable, as there is certainly no such thing as a 1000-digit long credit card. But if you really want that functionality, you'll have to write the script yourself or find another plugin. As of this time I'm not aware of one.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With