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"
Height="100"
Width="100"
>
<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" />
</asp:ListBox>
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"
TargetControlID="txtTitle"
DropDownControlID="lstTitles"
/>
This will give you a TextBox that has a down arrow that will open up the ListBox. But when you click the ListBox, it just goes away. So we'll add some JavaScript magic to the onclick event in order to populate the value in your TextBox with the value from the ListBox.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
lstTitles.Attributes.Add("onclick", "setText(this.options[this.selectedIndex].value);");
}
}
Now that we've applied the onClick handler, we just need to write the onClick function.
<script type="text/javascript" language="javascript">
function setText(newValue)
{
document.getElementById("<%=txtTitle.ClientID %>").value = newValue;
}
</script>
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.
|