Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: Javascript
Hi,
 
I have a Dropdown and a Textbox. When the user selectes Phone, Fax, SMS from drop down , the textbox should be in auto phone format.
 
i.e the user can enter only number and the phone format should be like (999) 99 - 9999. This validation depends on the dropdown value.
 

 

 
Presently I am using the following javascript funtion for individual textboxes
 
function FormatedPhone(e) {
                
                    evt = e || window.event;
                    var keyPressed = evt.which || evt.keyCode;
                    
                    if (((keyPressed >= 97) && (keyPressed <= 122)) || ((keyPressed >= 65) && (keyPressed <= 90)) || (keyPressed == 59)) {
                        return false;
                    }
                    else {
                        if (keyPressed == 8 || keyPressed == 37) {
                            return;
                        }
 
                        var target = evt.target || evt.srcElement;
 
                        phone = target.value;
                        if (phone.length == 1 && phone != "(") {
                            target.value = "(" + phone;
                        }
                        else if (phone.length == 4 && phone.substring(0, 1) == "(" && !isNaN(phone.substring(1, 4))) {
                            target.value = phone + ") ";
                        }
                        else if (phone.length == 9 && phone.substring(0, 1) == "(" && !isNaN(phone.substring(1, 4)) && phone.substring(4, 5) == ")" && !isNaN(phone.substring(6, 9))) {
                            target.value = phone + "-";
                        }
                    }
                }
 
and I am calling this javascript funtion in .cs Page load by adding the attributes
 
txtPhone1.Attributes.Add("Onkeypress", "return FormatedPhone(event)");
 

Please any body help me to format the javascript funtion according to my requirement ( accroding to dropdown value)
 

 
Thanks,
 
Nag
Posted 4-Apr-13 6:21am

1 solution

Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

What you are looking for is a masked input.
This[^] javascript library has helped me in the past and seems reasonably solid for that purpose.
 
If you have multiple different formats specified by a dropdown that then need to be applied to a text input, then you'll just have to change the mask on the fly and re-validate the textual content.
  Permalink  
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



Advertise | Privacy | Mobile
Web03 | 2.8.1411022.1 | Last Updated 4 Apr 2013
Copyright © CodeProject, 1999-2014
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100