|
|
Fill TextBoxes with Java Script on DropDownList SelectedIndexChangeCreating a JavaScript Array Dynamically at Runtime. | | How do I fill TextBoxes from an ASP.NET DropDownList SelectedIndexChange? Sometimes you wish you could get completely away from JavaScript, but at the same time a little ingenuity and work will greatly improve the responsivness of your ASP.NET Application. JavaScript can be a real pain; either you get it exactly right or it will not work.
In an application I am working on, the page is basically a Wizard with several steps, three of which need to fill a set of 5 TextBoxes when the user selects a value from a DropDownList located above the TextBoxes. I started doing this in CodeBehind, but obviously, that requires a PostBack to the Server and results in page refresh. The neat thing is that it can be done with JavaScript and eliminate both the PostBack and the trip to the server. This article will show all of the code required to accomplish this trick.
For this application, I am importing first name, last name, and phone number from a text/csv file. However, the DropDownList can contain the three fields in any order. So I have to let the user tell me which field is which. I then record the index of the DropDownList after the selection. In addition, I fill up to 5 text boxes with the corresponding field from the input file. First, I need to build, in the CodeBehind, a two dimensional array and save it to the page in a Literal control. From then on the array will be persisted in ViewState by the Literal control. This is done by calling the method shown below in Figure 1.
Figure 1 - Creating a JavaScript Array in Code.
/// <summary>
/// Return string of a javascript matrix[numFields, 5]
/// </summary>
/// <returns>string</returns>
private string GetFiveRowsAllColumnsArray()
{
bool headerExtant = (VSHdrYesNo == "Yes");
string patt = VSParsePattern;
StreamReader sr = new StreamReader(VSFileName);
int linesRead = 0;
int numFields = 0;
string line = sr.ReadLine();
string[] lineArray;
string[,] allFields;
// read one line to get the number of fields to dimension the array
if (line != null && line.Trim().Length > 0 && linesRead < 5)<BR>
{
// if header not present, close the file and reopen to get back
// ready to read the first line of data
if (!headerExtant)
{
sr.Close();
sr = new StreamReader(VSFileName);
} // if
Match m = Regex.Match(line, patt, RegexOptions.ExplicitCapture);
if (!m.Success)
{
throw new Exception("Parsing error with regex in GetFiveRowsAllColumnsArray.");
} // if
numFields = m.Groups["field"].Captures.Count;
allFields = new string[numFields, 5];
// initialize all fields to ""
for (int y = 0; y < 5; y++)<BR>
{
for (int x = 0; x < numFields; x++)<BR>
{
allFields[x, y] = string.Empty;
} // for
} // for
} // if
else
{
return null; // file has no rows
} // else
linesRead = 0;
// array is dimensioned, populate it
for (int y = 0; y < 5; y++)<BR>
{
while (linesRead <= 5)<BR>
{
line = sr.ReadLine();
if (line == null)
{
break;
} // if
else if (line.Trim().Length < 1)<BR>
{
continue;
} // else
linesRead++;
break;
}
if (line == null)
{
break;
}
Match m = Regex.Match(line, patt, RegexOptions.ExplicitCapture);
if (!m.Success)
{
throw new Exception("Parsing error with regex");
} // if
lineArray = new string[m.Groups["field"].Captures.Count];
for (int x = 0; x < numFields; x++)<BR>
{
allFields[x, y] =
m.Groups["field"].Captures[x].Value.Replace("\"", "").Trim();
}
} // for
// we have the initial array, build the javascript matrix array
StringBuilder sb = new StringBuilder(2000);
sb.Append("" + Environment.NewLine);
return sb.ToString(); // change to return the string
} // method: GetFiveRowsAllColumnsArray
|
The output from this method will be a string containing a JavaScript Array as shown in Figure 2 below:
Figure 2 - Output form GetFiveRowsAllColumnsArray.
<script type="text/javascript">
<!--
var matrix = new Array(3);
matrix[0] = new Array(5);
matrix[0][0] = "Josh";
matrix[0][1] = "Sally";
matrix[0][2] = "Adam";
matrix[0][3] = "";
matrix[0][4] = "";
matrix[1] = new Array(5);
matrix[1][0] = "Jones, Jr";
matrix[1][1] = "Jones";
matrix[1][2] = "Doe Jr";
matrix[1][3] = "";
matrix[1][4] = "";
matrix[2] = new Array(5);
matrix[2][0] = "8633135544";
matrix[2][1] = "8633135542";
matrix[2][2] = "86433135549";
matrix[2][3] = "";
matrix[2][4] = "";
// -->
</script> |
This string will be saved in an ASP.NET Literal Control, which will make the "matrix" array accessible to JavaScript Functions called to fill the text boxes. The JavaScript, show in Figure 3 below, will be saved in script file and a reference to the file will be placed in the ASPX page. The function shown below fills only the text boxes related to first names. The JS for the last name and phone number would be essentially the same with only the names of the controls being changed.
Figure 3 - JavaScript to Fill the First Name Text Boxes.
function FillFNTextBoxes(sender)
{
var pre = sender.id.replace("ddlFirstNames", "");
var FName = document.getElementById(pre + "ddlFirstNames");
var idx = Number(FName.selectedIndex);
var T1 = document.getElementById(pre + "txtSampleFN1");
var T2 = document.getElementById(pre + "txtSampleFN2");
var T3 = document.getElementById(pre + "txtSampleFN3");
var T4 = document.getElementById(pre + "txtSampleFN4");
var T5 = document.getElementById(pre + "txtSampleFN5");
if(idx > 0)
{
T1.value = matrix[idx - 1][0];
T2.value = matrix[idx - 1][1];
T3.value = matrix[idx - 1][2];
T4.value = matrix[idx - 1][3];
T5.value = matrix[idx - 1][4];
// so we don't hit the server, however there is
// no codebehind involved on the dropdownlist chang
return false;
}
}
|
In the Page_Load event, I will set the attributes of the DropDownLists to have a "onchange" event that will call the JaveScript event of the respective DDL into the ASPX page with the following code.
ddlFirstNames.Attributes.Add("onChange", "return FillFNTextBoxes(this);");
ddlLastNames.Attributes.Add("onChange", "return FillLNTextBoxes(this);");
ddlPhoneNumbers.Attributes.Add("onChange", "return FillPNTextBoxes(this);");
|
When the user makes a selection from the respective DropDownList, the JavaScript function associated with that list is called by the "onchange" event. CodeBehind has no event code for the DropDownLists and therefore it is never called and the text boxes are filled without a trip to the server or any refresh (and corresponding screen flash) of the page.
Need to automatically organize your code windows? You'll be amazed how easy it is to keep the code in your code windows organized. TRY IT FREE FOR 30 DAYS BY CLICKING HERE.
Automatically generate braces in C#! Try CSharpCompleter and stop wasting valuable time needlessly typing hundreds of braces {} daily. Try CSharpCompleter for 30 DAYS FREE.
| Ask a Question, or give your feedback on my articles or products by going to the KnowDotNet Forum or by clicking on My Blog. |  |
You can also email me directly at les@KnowDotNet.com.
|
|