Wednesday, May 2, 2007

Auto jump JavaScript – like phone number text boxes

If we want to build a set of text boxes that set focus to next control when set length of text if filled, one way we can do so is by writing JavaScript for key strokes and counting characters filled. Let’s jump into the code on how I do this:

StringBuilder sbJS = new StringBuilder();

sbJS.Append("<script language=javascript> ");

sbJS.Append("var isNN = (navigator.appName.indexOf(\"Netscape\")!=-1); ");

sbJS.Append("function autoTab(input,len, e) {");

sbJS.Append(" var keyCode = (isNN) ? e.which : e.keyCode;");

sbJS.Append(" var filter = (isNN) ? [0,8,9] : [0,8,9,16,17,18,37,38,39,40,46];");

sbJS.Append(" if(input.value.length >= len && !containsElement(filter,keyCode)) {");

sbJS.Append(" input.value = input.value.slice(0, len);");

sbJS.Append(" input.form[(getIndex(input)+1) % input.form.length].focus();");

sbJS.Append(" }");

sbJS.Append(" function containsElement(arr, ele) {");

sbJS.Append(" var found = false, index = 0;");

sbJS.Append(" while(!found && index < arr.length)");

sbJS.Append(" if(arr[index] == ele)");

sbJS.Append(" found = true;");

sbJS.Append(" else");

sbJS.Append(" index++;");

sbJS.Append(" return found;");

sbJS.Append(" }");

sbJS.Append(" function getIndex(input) {");

sbJS.Append(" var index = -1, i = 0, found = false;");

sbJS.Append(" while (i < input.form.length && index == -1)");

sbJS.Append(" if (input.form[i] == input)index = i;");

sbJS.Append(" else i++;");

sbJS.Append(" return index;");

sbJS.Append(" }");

sbJS.Append(" return true;");

sbJS.Append("}");

sbJS.Append("</script>");

//Register client script

if (!Page.ClientScript.IsClientScriptBlockRegistered("jsAutoFocus"))

Page.ClientScript.RegisterClientScriptBlock(GetType(),

"jsAutoFocus",

sbJS.ToString());

//Add JS to your textboxes...

tbxArea.Attributes.Add("onKeyUp", "return autoTab(this, 3, event);");

tbxLocal3.Attributes.Add("onKeyUp", "return autoTab(this, 3, event);");

tbxLocal4.Attributes.Add("onKeyUp", "return autoTab(this, 4, event);");

Love coding!

4 comments:

Anonymous said...

ty.easy to implement.

Anonymous said...

Thanks for the post. I couldn't find any code better than this one.

Thanks again.

Nico

Bas said...

nice code works great!

moni said...

Es fantástico, sin necesidad de adaptarlo... Gracias!!!