Tuesday, November 29, 2011

Clunky old Javascript input mask

 

I was working with the MaskedEditExtender recently to control input into some textboxes but got fed up with the “quirks” of it – namely the inability of it to select() the value of the textbox as well as weirdness of the masks in general.   For instance, if you were working with a currency mask set up as #,###.## and blurred off of the control and then went back to it (focus) your cursor would appear at the left-most character instead of the right-most.   This required an extra click to edit the value if you didn’t feel like retyping the entire thing.

Be that as it may, I still liked the ability to limit the keys used on the inputs and used a trusty old JavaScript function to achieve just that.  

My function uses passed variables to determine which keycodes to allow and what not to.   It’s a little clunky but it does the trick.  Simply specify the keys you’ll allow (by passing a “1) and which ones will be ignored (passing any other value besides “1”)

function LimitInput(NumbersOK, DecimalPointOK, CommasOK, QuotesOK, AlphaOK, SpacesOK, DateTimeSymbolsOK) {
x = window.event.keyCode;

// 0-9 on top row keys as well as num-pad
if (NumbersOK == 1 && ((x >= 48 && x <= 57) || (x >= 96 && x <= 105))) return true;

// decimal point and period key
if (DecimalPointOK == 1 && (x == 190 || x == 110)) return true;

//commas
if (CommasOK == 1 && x == 188) return true;

//single and double quotation marks
if (QuotesOK == 1 && x == 222) return true;

//letters only - upper and lower
if (AlphaOK == 1 && x >= 65 && x <= 90) return true;

// spacebar
if (SpacesOK == 1 && x == 32) return true;

// the dash, colon and forward-slash symbols
if (DateTimeSymbolsOK == 1 && (x == 191 || x == 109 || x == 16)) return true;

//always allow Backspace, Delete, TAB and Left/Right arrow keys
if (x == 46 || x == 8 || x == 9 || x == 37 || x == 39) return true;

return false;
}



Usage  Simply wire-up a call to this function from the control’s onkeydown event as such:


TextBox1.onkeydown = return LimitInput(#,#,#,#,#,#,#);


Example:  Wiring up a textbox “TextMoney” in code-behind so it only accepts currency-formatted input would look like


TextMoney.Attributes.Add("onkeydown", "return LimitInput(1,1,1,0,0,0,0);");


TIP:  Always remember to include “return” when making the call or else it won’t work Smile

No comments: