Click here to Skip to main content
Email Password   helpLost your password?

Introduction

Some times when creating forms, we like to use something that's called an "input mask". An input mask is something that, (most times) as you're typing in (let's say) a text box, certain characters will automatically be entered into the textbox.

For example: if I had a text box that is supposed to hold a phone number and I want the phone number to be formatted like so "111-111-1111", in such a case the input mask will automatically enter the "-" character after the third and sixth characters, in order that the user does not have to do it.

In my script, those characters MUST be included.

Script breakdown and explanation

<form name="form" action="" method="post">

<input name="Field1" value="" type="text" 

onKeyUp="javascript:return mask(this.value,this,'3,6','-');"

onBlur="javascript:return mask(this.value,this,'3,6','-');"

style="font-family:verdana;font-size:10pt;width:110px;"

maxlength="11">

</form>

The first 3 lines are (hopefully) self understood, however I will explain them: the <form> tag can be edited, although all that needs editing is the action="".

The <INPUT> tag is set to call the JavaScript function (below) named mask, it passes 4 parameters to the function,

  1. str - the value of the current textbox control,
  2. textbox - the actual textbox object, (so that the value can be set)
  3. loc - a string of multiple locations to place the specified character,
  4. delim - the character (delimiter) that you want to use a separator.

The maxlength value is set to a length of 11 since I would like 9 characters and 2 "-" characters.

The mask function is called in 2 places (1: onKeyUp, so that as the user types, the field will be edited, 2: onBlur, this is not needed, but it's just in case)

Below is the function line by line explained:

function mask(str,textbox,loc,delim){

Begins the function with a name mask, and sets 4 parameters, as mentioned above.

var locs = loc.split(','); 

Creates an array out of multiple numbers (to add each separator on its own).

for (var i = 0; i <= locs.length; i++){

Begins a loop through the array of locations.

for (var k = 0; k <= str.length; k++){

Begins a nested loop through each character to check if the delimiter is already there.

if (k == locs[i]){

Begins a conditional statement that checks to see what character number we are holding.

if (str.substring(k, k+1) != delim){

Begins a nested conditional statement if the character we're holding is the correct character location, and checks to see if it is the same character as the delimiter.

str = str.substring(0,k) + delim + str.substring(k,str.length)

if the character is not the same as the delimiter, it will cut the value in half and insert the delimiter

}

}

}

}
textbox.value = str

This sets the value of the textbox control being edited

}

There you have it, the complete script. If you would like to test the script, click here.

Conclusion

Nothing in the function needs editing, and only the last 2 parameters of the textbox that calls the function should be edited, although a user can do as he wills.

Notes:

This script works well in Netscape 6+ and IE 4+. In Netscape 4, after the JavaScript edits the field, the cursor will go to the beginning of the field (this can be fixed).

You must Sign In to use this message board.
 
 
Per page   
 FirstPrevNext
GeneralHelp with Jquery
smarika
17:53 11 Jan '10  
I was trying to mask the inputs phone, email and zipcode using Jquery but it is not working...
Can you help me?

<%
using (Ajax.BeginForm("SaveContact", null,
new AjaxOptions
{
//OnBegin = "contactEditorDialogPrepare",
OnComplete = "contactEditorDialogComplete",
Confirm = Model.ConfirmMessage,
LoadingElementId = "collateralBusyMessageBox",
//UpdateTargetId = "contactData" + item.ID,
}, new { @class = "embeddedForm", id = "ContactEditorForm" }))
{%>
Contact Information <%--
Save
<img alt="save" title="Save contact" width="24" height="24" src="<%= Url.Content( "~/Images/floppy_disk_48.png")%>" />
--%>
<% for (int i = 0; i < Model.Collateral.Items.Count; i++)
{
if (Model.Collateral.IsImage(i))
{
%>
<%= Html.CollateralImage(Model.Collateral.ID, i, 150, new
{
@class = "collateralImage",
})%>
<%
}
} %>
<script src="~scripts/jquery/jquery-1.3.2.min.js" type="text/javascript"></script>
<script src="~scripts/jquery/jquery.maskedinput-1.2.2.min.js" type="text/javascript"></script>
Contact Name
<input id="id" name="id" type="hidden" value="<%= Model.Collateral.ID %>" />
<%= Html.TextBox("firstName", Model.Contact.FirstName, new
{
maxlength = Limits.ContactNameLength,
size = 8,
})
%>
<%= Html.ValidationMessage("firstName", "*")%>
<%= Html.TextBox("middleName", Model.Contact.MiddleName, new
{
maxlength = 1,
size = 1,
})
%>
<%= Html.ValidationMessage("middleName", "*")%>
<%= Html.TextBox("lastName", Model.Contact.LastName, new
{
maxlength = Limits.ContactNameLength,
size = 8,
})
%>
<%= Html.ValidationMessage("lastName", "*")%>
<%= Html.ValidationMessage("name", "*")%>
Company
<%= Html.TextBox("company", Model.Contact.Company, new
{
maxlength = Limits.ContactCompanyLength,
size = 15,
})
%>
<%= Html.ValidationMessage("company", "*")%>
Title
<%= Html.TextBox("title", Model.Contact.Title, new
{
maxlength = Limits.ContactTitleLength,
size = 15,
})
%>
<%= Html.ValidationMessage("title", "*")%>
Address1
<%= Html.TextBox("address1", Model.Contact.Address1, new
{
maxlength = Limits.ContactAddressLength,
size = 15,
})
%>
<%= Html.ValidationMessage("address1", "*")%>
Address2
<%= Html.TextBox("address2", Model.Contact.Address2, new
{
maxlength = Limits.ContactAddressLength,
size = 15,
})
%>
<%= Html.ValidationMessage("address2", "*")%>
City/State/Zip
<%= Html.TextBox("city", Model.Contact.City, new
{
maxlength = Limits.ContactCityLength,
size = 10,
})
%>
<%= Html.ValidationMessage("city", "*")%>
<%= Html.TextBox("state", Model.Contact.State, new
{
maxlength = Limits.ContactStateLength,
size = 2,
})
%>
<%= Html.ValidationMessage("state", "*")%>
<%= Html.TextBox("zip", Model.Contact.Zip, new
{
maxlength = Limits.ContactZipLength,
size = 8,
})
%>
<%= Html.ValidationMessage("zip", "*")%>
<%= Html.ValidationMessage("cityStateZip", "*")%>
Work Phone
<%= Html.TextBox("phone1", Model.Contact.CompanyPhone, new
{
maxlength = Limits.ContactPhoneLength,
size = 10,
})
%>
<%= Html.ValidationMessage("phone1", "*")%>
<%= Html.TextBox("phoneExt1", Model.Contact.CompanyExt, new
{
maxlength = Limits.ContactExtLength,
size = 4,
})
%>
<%= Html.ValidationMessage("phoneExt1", "*")%>
Fax
<%= Html.TextBox("fax", Model.Contact.CompanyPhone, new
{
maxlength = Limits.ContactPhoneLength,
size = 10,
})
%>
<%= Html.ValidationMessage("fax", "*")%>
Mobile Phone
<%= Html.TextBox("mobile", Model.Contact.MobilePhone, new
{
maxlength = Limits.ContactPhoneLength,
size = 10,
})
%>
<%= Html.ValidationMessage("mobile", "*")%>
email
<%= Html.TextBox("email", Model.Contact.EmailAddress, new
{
maxlength = Limits.ContactEmailLength,
size = 20,
})
%>
<%= Html.ValidationMessage("email", "*")%>
Notes
<%= Html.TextBox("notes", Model.Contact.Note, new
{
maxlength = Limits.NoteLength,
size = 20,
})
%>
<%= Html.ValidationMessage("notes", "*")%>
<%} %>

GeneralA small problem.
wer@_op03
23:23 24 Sep '08  
Hi,
I have a text box with maxlength set as 10. I want the '-' to enter at the 5th position. But in firefox, the positioning of cursor differs. I'm not supposed to increase the width of the textbox. how to go about with it??

P.S: The logic works fine. Just the look and feel
GeneralRe: A small problem.
wer@_op03
23:39 24 Sep '08  
I mean to say if you reduce the textbox width given in the code to 70px
and try in firefox, you will understand my problem.
Generalrequired field validator
rsgrady
21:54 12 Oct '07  
When I use a RequiredFieldValidator on this custom control, the client side validation fails. Any ideas?
GeneralRe: required field validator
webProgrammer
18:26 16 Oct '07  
please provide some sample code so I can better understand what you're doing and what you're trying to do.
GeneralRe: required field validator
rsgrady
22:22 19 Oct '07  
When an ASP.NET RequiredFieldValidator is set to validate a regular textbox, the Text of the validator is hidden when data is entered into the textbox. This does not happen in the custom control when it is validated by the validator. It does operate as expected on postback.
GeneralRe: required field validator
webProgrammer
12:28 21 Oct '07  
Again, please provide some sample code so that I can actually see what you're trying to do.
QuestionEditing?
Umer Khan
1:32 19 Jul '07  
hey
here is a big bug ?Frown
when you start to edit text box, it doesn't change it
rather it move cursor to the end of text
AnswerRe: Editing?
Chris_CP
14:34 7 Aug '07  
This version of the method fixes the editing problems for this otherwise great script. It allows you to backspace and also left arrow, right arrow and press the delete key through the text so you can edit any mistakes you have made cleanly without loosing the functionality of inserting the specified characther that you want.

This link shows all the keyCodes of javascript (each represents a keyboard value - a, b, backspace etc)
http://www.cambiaresearch.com/c4/702b8cd1-e5b0-42e6-83ac-25f0306e3e25/Javascript-Char-Codes-Key-Codes.aspx[^]

The reason it goes to the end of the page is due to setting the value of textbox to anything. If you post any value like this it will automatically go to the end. Hence if you surround it with the catching if statement like I have you can still edit the text quite happily without it going to the end of the line.

There was no bug in this program, it was just designed without the editing functionality in mind, as you can see it's easy enough to add. Hope this helps.

function mask(str,textbox,loc,delim){
var locs = loc.split(',');
for (var i = 0; i <= locs.length; i++){
for (var k = 0; k <= str.length; k++){
if (k == locs[i]){
if (str.substring(k, k+1) != delim){
if (event.keyCode != 8){ //backspace
str = str.substring(0,k) + delim + str.substring(k,str.length)
}
}
}
}
}
if (event.keyCode != 37 && event.keyCode != 39 && event.keyCode != 46) {
textbox.value = str;
}
}
QuestionMore Than one Delimare
yaseencarter
3:32 18 Jul '07  
Example;(222) 222-2222
what changes are required for above example

muhammad yasin

Question(232) 232-2323 how to do thta
Umer Khan
0:54 18 Jul '07  
its really really nice thing
great work
can you provide me help regarding this format
(232) 232-2323

??
GeneralThanks!
sweettomandjerry
16:45 4 Apr '07  
This is great! Thanks!!
GeneralGreat tool!
gogetsome
5:49 28 Jul '06  
Hello, I've look far and wide for a simple solution for an input mask. Your's works great for masking 111-111-1111. I have a slight variation that I'm trying to do like: (111) 111-1111

Is it possible for your code to be changed to do it that way?
GeneralJumps to beginning of field
daddion
7:46 19 Sep '05  
I am using IE6. When I tab into some of the fields with the input mask it moves to the front of the textbox instead of highlighting the textbox as normal. Not on every textbox assigned the input mask, but always on the same ones.
GeneralRe: Jumps to beginning of field
daddion
7:54 19 Sep '05  
The problem only occurs when coming from other textboxes. If I enter from a dropdownlist, for example, it works - the textbox is highlighted and the user can start typing. I think it is capturing the tab up keyup event.
GeneralRe: Jumps to beginning of field
daddion
8:37 19 Sep '05  
Sorry to keep replying to myself, but the modify message is broken at the moment. I solved it by adding this to the beginning of the script:

if (event.keyCode == 9)
return false;
Generalfirefox
Anonymous
18:52 12 Nov '04  
It doesn't work with firefox 1.0...
GeneralNetscape
Anonymous
11:49 20 Jan '04  
There's some weird stuff occurring when you try to run this script in Netscape. The events are not being handled properly. Any thoughts?
GeneralRe: Netscape
webProgrammer
12:29 20 Jan '04  
what version of netscape?


GeneralRe: Netscape
Anonymous
4:52 21 Jan '04  
I'm using version 7.1. Works like a charm in I.E. but I believe that Netscape's event handling is not up to snuff. I.E. handles the onKeyUp events while Netscape just lets them go by. If you get a chance to try it with 7.1 please do so. We may need to do so before we blame Netscape for its inadequacies Smile . Also, the fix that you used to capture the backspace event may not work with Netscape. (e.which) may need to be used in this case. I'll have to sniff the browser then incorporate this event handler. Please let me know if you encounter the same problem as it may be native to my machine. Thanks.
GeneralRe: Netscape
webProgrammer
8:43 21 Jan '04  
if I understand things correctly, the reason it's not working at all in netscape is because netscape is returning a javascript error when it get's to the "event.keyCode" - since netscape does not recognize this command it will not go further.
in netscape what you would have to do is first capture the event and then check what occured. - for example
<script> window.onKeyPress = captureKey();

function captureKey(e) {
if (document.all) {
nKeyCode = event.keyCode;
} else{
nKeyCode = e.keyCode
}
}
</script>

- I did not test this code, however this should work.

GeneralAnother bug
bm_ross
18:30 15 Sep '03  
This code is great except there is one other issue also.

If you highlight the hyphen and type another number then it adds extra characters.
QuestionRe: Another bug
Umer Khan
2:44 28 Sep '07  
did u find the solutiohn of this bug?
GeneralDeleting Field information
Eric Bennion
4:52 19 Aug '03  
After I entered my data, I realized it was wrong, so i tried to go back and change it, but the script wants to re-insert the delimiter each time I delete it. I tried to tab from field to field, which normally selects the data in the field, but for some reason the data briefly is selected and then the block dissapears. I finally was able to delete the fields by tabbing and immediately hitting my delete key. It took a few tries, but I was finally able to do it. Is there an easier way to change the data in a field?
GeneralRe: Deleting Field information
Eric Bennion
5:04 19 Aug '03  
It's me again...I realized that a reset button would take care of the problem. Big Grin

<input type = "reset" value="Reset">


Last Updated 20 Aug 2003 | Advertise | Privacy | Terms of Use | Copyright © CodeProject, 1999-2010