Have implemented a function (for a site that am working on) to simultaneously format a phone number while the user is entering the number into the input field . THe front end has been coded using html/css angularjs(though am not very efficient in angular js). Am calling the formatting function using ng-change directive. Below is the function that is being called and the formatting takes place when the user enters 7th numeric digit.
$scope.FormatPhnNo =function(){
var elem = angular.element("#userId");
var userID=$scope.userId.replace(/[^\w\@\.]/g, '');
userID= userID.replace(/\s/g,'');
var formattedId;
if(isNaN(userID)){
$scope.userId=userID;
return;
}
else{
if(userID.length < 7 || userID.length>10){
$scope.userId=userID;
}
else if((userID.length > 6 && userID.length<11)) {
var ctnArray=[];
for (var i = 0, len = userID.length; i < len; i += 1) {
if(ctnArray.length == 0){
ctnArray[0]="(";
}
else if(ctnArray.length ==4){
ctnArray[4]=")";
ctnArray[5]=" ";
}
else if(ctnArray.length ==9){
ctnArray[9]="-";
}
ctnArray.push(+userID.charAt(i));
formattedId=ctnArray.join().replace(/[,]/g, '');
}
elem[0].value = '';
elem[0].value = formattedId;
}
}
};
directly assigning the formatted value to model wasn't working properly in some version of chrome so changed the value using element. However now the function works fine on browser but create a no of issues on mobile browser. mostly cursor placement issues which happens when on launching the app for the first time and enter some values. if I remove all the entered data in that field and then type again it works fine. Also after the formatting starts taking place i.e when the user enter 7ts digit after the the cross button on mobile keypad to remove text stops functioning. Is there a better way to achieve this functionality . Didn't want to use element directly but the model wasn't updating any other way . this needs to be on ng-change can't have this function on blur as that's a requirement