Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

javascript - 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);

    }
}

});
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...