What is the best way to place dashes in the phone field with JavaScript?
Asked
Active
Viewed 89 times
-4
-
Try this one http://stackoverflow.com/a/20154573/1181310 is already answer – Adrian Bolonio May 06 '15 at 08:09
1 Answers
1
Use this, maybe, it is too complex, but such code works (here was used http://www.jstorage.info/):
function addPhoneListener(element) {
if (!(element instanceof jQuery)) {
element = $('#' + element.id);
}
var maxLength = 20;
var firstDashIndex = 5;
var secondDashIndex = 9;
var thirdDashIndex = 12;
save('hasPreviousEnded', 'false');
function process() {
var clearPhone = element.val().replaceAll('-', '');
var length = clearPhone.length;
if (!/^\d+$/.test(clearPhone) || length > maxLength) {
element.val(length > 0 ? element.val().substring(0, maxLength) : '');
}
function placeDashes(array) {
if (element.val() !== '-'
&& !isEmpty(element.val())) {
for (var i = 0; i < array.length; i++) {
if (!equals(element.val().charAt(array[i]), '-')
&& element.val().length >= array[i]) {
element.val(element.val().substring(0, array[i]) + '-' + element.val().substring(array[i],
element.val().length));
}
}
}
if (element.val().length >= maxLength && element.val().charAt(element.val().length - 1) === '-') {
element.val(element.val().substring(0, element.val().length - 1));
}
}
if (Number(saved('previousDashPlacing')) + 85 < new Date().getTime()) {
placeDashes([firstDashIndex, secondDashIndex, thirdDashIndex]);
save('previousDashPlacing', new Date().getTime());
}
}
process();
element.on('keyup', function () {
process();
})
function save(key, data) {
if (typeof data === 'object') {
data = toJSON(data);
}
$.jStorage.set(key, data, null);
}
}

Arthur
- 1,156
- 3
- 20
- 49