If we want to format the phone number on user input, we can handle it with keypress event using Jquery.
here is sample code to force the user can input 10 number and automatically format them to be
XXX-XXX-XXXX
$("#phoneNumberInput").keypress(function (e) {
if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
return false;
}
var currentChar = this.value.length;
var currentValue = $(this).val();
if (currentChar == 3) {
$(this).val(currentValue + "-");
} else if (currentChar == 7) {
$(this).val(currentValue + "-");
}
$(this).attr('maxlength', '12');
});
in KnockoutJs, we can implement a custom binding handler, then we can apply it to all phone number input fields,
with the keydown event to prevent any non numeric value.
update function in the handler will format the text change to the specific format after user enter 10 nueric values.
ko.bindingHandlers.formatPhoneNumber = {
init: function (element, valueAccessor) {
$(element).on("keydown", function (event) {
if (event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 27 || event.keyCode == 13 ||
(event.keyCode == 65 && event.ctrlKey === true) ||
(event.keyCode == 188 || event.keyCode == 190 || event.keyCode == 110) ||
(event.keyCode >= 35 && event.keyCode <= 39)) {
return;
}
else {
if (event.shiftKey || (event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105)) {
event.preventDefault();
}
}
});
},
update: function (element, valueAccessor) {
$(element).val(ko.unwrap(valueAccessor()));
formatPhone(element);
}
};
formatPhone = function (element) {
var phone= $(element).val().replace(/(\d{3})(\d{3})(\d{4})/, "$1-$2-$3");
$(element).val(phone);
}
it is very easy to use in the html page. here we will use textInput Binding from KnockoutJs framework to trigger the formatPhoneNumber update method immediately after the user key in 10 numbmers.
<input id="phone" class="form-control" type="text" placeholder="Home Phone" data-bind="textInput: homePhone, formatPhoneNumber:homePhone, validationElement:homePhone " maxlength="10" />
No comments:
Post a Comment