therealbigpepe
therealbigpepe

Reputation: 1549

Split into separate fields an input text

I'm having a trouble when i try to force the user to enter data to a text input. I need to do something like the IP Address input in Windows. Ip Adress Input

I want to split the text input by dashes having something like this 10 - 10 - 10 - 10

Is there any way to do this ?

Upvotes: 0

Views: 1536

Answers (1)

MortenMoulder
MortenMoulder

Reputation: 6648

http://jsfiddle.net/87dug9oa/1/

function check(text) {
    var result = [];
    text = text.replace(/[^\d]/g,"");
    while (text.length >= 3) {
        result.push(text.substring(0, 3));
        text = text.substring(3);
    }
    if(text.length > 0) result.push(text);
    $("#ip").val(result.join("-"));
}

$("#ip").on("keyup", function() {
    check($(this).val());
});

This creates a function, which adds dashes once 3 characters has been added (and the fourth is written).

Now, this does do what you want, but you need to add some additional stuff, such as checking for length and making the remove part work (because when you press any key, it will change the input's value, which will make the caret move to the last character).

Oh I almost forgot. This can be changed to the length of your choice, of course. Just change the "3" to be something else.

Upvotes: 4

Related Questions