Muneeb Hassan
Muneeb Hassan

Reputation: 63

How to insert hyphen "-" after 4 digits automatically in TextBox in html5?

I have made validation in input field in html5 to get this format 03xx-xxxxxxx.

pattern="03\d{2}-\d{7}"

Now I want to add this hyphen symbol automatically after fourth digit.How to do that?

Upvotes: 3

Views: 2462

Answers (2)

rafaelcastrocouto
rafaelcastrocouto

Reputation: 12161

I must advice you against this type of input edit since it's usually frustrating when you need to edit typos.

Also I have no idea of the issues related to accessibility.

The input pattern only checks the data on submit, so it's not what you are looking for.

That said, here's one possible solution in JS:

// select the input element
var i = document.querySelector('input.hyphen');
// number of charatcers before the hyphen
var n = 4;
// run this function everytime the user release a key
i.addEventListener('keyup', function (event) { 
  // if there are more then n digits
  if (i.value.length > n) {
    // save the carret position
    var s = i.selectionStart;
    // remove all dashes
    var t = i.value.replace(/-/g, '');
    // beginning string with n digits
    var b = t.substr(0, n);
    // end string with what's left (maxLength)
    var e = t.substr(n);
    // join then with a dash
    i.value = [b, e].join('-');
    // if the caret was before the dash put it back to the saved position
    if (s <= n) i.setSelectionRange(s, s);
    // if the caret was next to the dash put it after
    if (s == n+1) i.setSelectionRange(s+1, s+1);
  }
});
<input class="hyphen" placeholder="0000-0000000" maxlength="12">

Upvotes: 4

Rounin
Rounin

Reputation: 29453

I have made validation in input field in html5 to get this format 03xx-xxxxxxx.

One alternative approach (without javascript) is to use three <input /> fields.

Working Example:

#country,
#region {
width: 16px;
}

#local {
width: 56px;
}
<input type="text" id="country" value="03" readonly />
<input type="text" id="region" pattern="[0-9]{2}" placeholder="88" />
-
<input type="text" id="local" pattern="[0-9]{7}" placeholder="8888888"/>

Upvotes: 1

Related Questions