When entering and displaying phone numbers, sometimes its annoying to read all numbers together. Because it may be hard to read. If we can add a space in between few numbers to make it masked, it would be ideal for the user to read it quickly.
It is easy with JQuery. Look at the below function.
This can be applied to the textboxes by binding the events below;
So the textbox will look like this;
This is a static method that remove the space. However, you may not need to apply this but if there is a restriction in the DB side, you can always use this.
Happy Coding... :)
It is easy with JQuery. Look at the below function.
function addSpace(control, flPaste) {
if (flPaste == false) {
var txtVal = $("#" + control).val();
if (txtVal.length == 2) {
$("#" + control).val($("#" + control).val() + " ");
flSpaceAdded = true;
}
else if (txtVal.length == 5) {
$("#" + control).val($("#" + control).val() + " ");
flSpaceAdded = true;
}
else if (txtVal.length == 8) {
$("#" + control).val($("#" + control).val() + " ");
flSpaceAdded = true;
}
else if (txtVal.length == 11) {
$("#" + control).val($("#" + control).val() + " ");
flSpaceAdded = true;
}
}
else if (flPaste == true) {
setTimeout(function () {
var txtVal = $("#" + control).val();
var txtValNew = "";
for (var i = 0, len = txtVal.length; i < len; i++) {
txtValNew += txtVal[i];
if (i == 1) {
txtValNew += " ";
}
else if (i == 3) {
txtValNew += " ";
}
else if (i == 5) {
txtValNew += " ";
}
else if (i == 7) {
txtValNew += " ";
}
}
$("#" + control).val(txtValNew);
}, 100);
}
}
This can be applied to the textboxes by binding the events below;
//for typing
$("#txtadPhone").keyup(function () {
addSpace("txtadPhone",false);
});
// for pasting
$("#txtadPhone").bind('paste', function (e) {
addSpace("txtadPhone", true);
});
So the textbox will look like this;
So you will have 14 characters for a 10 digit numbers here. Therefore you may need to cater it in the database or else you need to remove the space using a method in the codebehind. For example,
public static string removeSpace(string str)
{
if (str == null)
return null;
var vVal = string.Empty;
foreach (var v in str.ToCharArray())
{
if ((int)v == 32)
continue;
vVal += v.ToString();
}
return vVal;
}
This is a static method that remove the space. However, you may not need to apply this but if there is a restriction in the DB side, you can always use this.
Happy Coding... :)