Using AJAX to Create a DropDownList for Populating a TextBox
For an application I had to develop for work, we had a need for an input field that allowed you to either select an item or type in your own item. Before AJAX, you would have to write create your own ComboBox or create something like an "Other" selection and then have a blank TextBox for your new item. Thankfully today we have AJAX and can accomplish this rather easily using the DropDownExtender, a TextBox, and a ListBox. Because speed was an issue, we also wanted to keep everything clientside.
For this example, I am going to assume you already have AJAX setup for your web application. If not, I suggest going to Microsoft's AJAX website and following their instructions. It's a simple setup, expecially if you have Visual Studio 2008, and their walkthrus do a good job teaching you.
Begin by creating your TextBox and your ListBox. You could use most any other control instead of a ListBox (the Microsoft example uses a panel with LinkButtons), but by using a ListBox you have the option to easily bind it to a DataSource.
<asp:TextBox ID="txtTitle" runat="server" />
<asp:ListBox ID="lstTitles" runat="server"
<asp:ListItem Text="One" Value="One" />
<asp:ListItem Text="Two" Value="Two" />
<asp:ListItem Text="Three" Value="Three" />
<asp:ListItem Text="Four" Value="Four" />
<asp:ListItem Text="Five" Value="Five" />
Now create your DropDownExtender and set the TargetControlID to the ID of your TextBox and set the DropDownControlID to the ID of your ListBox.
<ajaxToolkit:DropDownExtender runat="server" ID="DDE"
protected void Page_Load(object sender, EventArgs e)
Now that we've applied the onClick handler, we just need to write the onClick function.
document.getElementById("<%=txtTitle.ClientID %>").value = newValue;
I used txtTitle.ClientID instead of just the ID of the TextBox so that this would work correctly within the confines of a Master Page.
Compile and run<
This article has been view 20703 times.