Tomas Jacobsen
Tomas Jacobsen

Reputation: 2416

Format input field to separate the first 4 digits with a period, and the next 2 digits with a period

I have a text-input with a placeholder value. Im wondering if it is possible to have a default value when the user clicks the input. The value should look like this: ____.__._____

The _ character in the value should be replaced with what the user is typing, but the period should stay in place.

Here is my input:

<input type="text" id="accountnumber" name="accountnumber" placeholder="Located on your card" />

Upvotes: 1

Views: 2041

Answers (3)

Greenhorn
Greenhorn

Reputation: 1700

You could use a plugin for this:

Masked Input plugin

Upvotes: 4

Krasimir
Krasimir

Reputation: 13529

My suggestion involves two fields. One over each other. Here is a demo http://jsfiddle.net/UCPxU/

HTML

<input type="text" class="template" value="____.__._____" />
<input type="text" id="accountnumber" name="accountnumber" placeholder="Located on your card" />

CSS

input {
    position: absolute;
    top: 0;
    left: 0;
}
input[name="accountnumber"] {
    background: none;
}

JS

var input = $("input[name='accountnumber']");
input.on("keyup", function(e) {
    var value = input.val();
    // catching backspace
    if(e.keyCode === 8) {
        if(value.length == 4) {
            input.val(value.substr(0, 3));
        } else if(value.length == 7) {
            input.val(value.substr(0, 6));
        }
    } else {
        if(value.length == 4) {
            input.val(value + ".");
        } else if(value.length == 7) {
            input.val(value + ".");
        }
    }
});

However, the solution works only if the user types every letter separately. If he for example press and hold 3 the keyup event is fired once, but the added characters are several. Anyway, this could be workarounded with setInterval or something like that.

Upvotes: 1

shankri
shankri

Reputation: 11

you can use input boxes of required length

ex:

<input type="text" maxlength="4">.<input type="text" maxlength="2">.<input type="text" maxlength="4">

Upvotes: 0

Related Questions