Question

I have a setup where a user can enter a zip code into an ASP.NET TextBox control, and I have an AutoCompleteExtender from the Ajax Control Toolkit attached to that textbox. It gets its data from a static page method on the ASPX page.

When the user starts typing a Swiss zip code, e.g. 3 and then waits a brief moment, a list of matching zip code shows up - something like:

3000 - Bern
3001 - Bern

and so on. Works like a charm.

The normal way to pick one of the options shown is to move your mouse pointer to the list and select the one you want, click on it or press Enter, and get the zip code into that textbox (and the city name into a second textbox next to it).

Now, I got some additional requirements from my project manager:

  1. we would like to be able to just press Enter without going into the list of choices to select one - he'd like to just get the first (or often times: only) entry shown put into those two textboxes...

  2. we would like to be able to enter a valid 4-digit zip code and then just press Tab and move out of the textbox for the zipcode, and have the first (possibly only) entry with that zipcode be chosen and "selected" (and stuffed into the two textboxes).

Seems like a tall order to me (I'm not a great Javascript guru at all.....) - any ideas?

This is my ASP.NET page (in a standard ASP.NET 4.0 webforms sample app - with a master page; the script is simplified; in reality, I'm splitting up the text 3001 - Bern at the dash and stick the first part into the zip code and the second part into the city textbox):

<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
    <script type="text/javascript">
        function IAmSelected(source, eventArgs) {
            $get('tbxCity').value = eventArgs.get_value();
        }
    </script>
    <asp:ScriptManager runat="server" EnablePageMethods="True" />

    <asp:Literal runat="server" ID="litPrompt" Text="Please enter zip code: " />
    <asp:TextBox runat="server" ID="tbxZipcode" MaxLength="10" />
    <act:AutoCompleteExtender runat="server" ID="acZipCode" TargetControlID="tbxZipcode" MinimumPrefixLength="1" 
                              CompletionInterval="25" ServiceMethod="GetMatchingZipCodes" CompletionSetCount="15"
                              OnClientItemSelected="IAmSelected" />
    <asp:TextBox runat="server" ID="tbxCity" MaxLength="50"  />
</asp:Content>

and my code-behind (this, too, is simplified - of course, in reality, I get this data from a Entity Framework data model):

[WebMethod]
[ScriptMethod]
public static string[] GetMatchingZipCodes(string prefixText, int count)
{
   return new string[] { "3000 - Bern", "3001 - Bern", "4000 - Basel", "6000 - Lucerne", "6001 - Lucerne" };
}
Was it helpful?

Solution

Check the FirstRowSelected property of AutoCompleteExtender. From your requirements seems like it's exactly what you need.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top