Question

I'm trying to write some JQuery using the AutoComplete plugin to display a list of names to the user as the user starts to type in the names (see code below). The code is working fine unless the user starts backspacing to change the name of the user entered, which causes it to write new values over the existing ones in the autocomplete results. Is there something I'm doing wrong here, maybe by using the keyup function to kick off the autocomplete, or is there some way to clear the existing autocomplete results if the user starts to backup?

Here is the JQuery code in the markup file in Default.aspx:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script type="text/javascript" src="js/jquery-1.3.2.js" ></script>
    <script type="text/javascript" src="js/jquery.autocomplete.js" ></script>  
    <script type="text/javascript">
    $(document).ready(function() {
        $("#example").keyup(function() {
            $.ajax({
                    type: "POST",
                    url: "Default.aspx/GetCustomerNames",
                    data: "{ searchParam: '" + $("#example").val() + "'}",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function(msg) {
                        $("#example").autocomplete(msg.d, 
                            { scroll: false, max: 10, width: 250, selectFirst: true });
                    }  
            });
        });
    });    
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>        
        Customer Name:  <input id="example" autocomplete="off" type="text" />      
    </div>
    </form>
</body>
</html>

And here is the code in my Default.aspx.cs codebehind file returning the data:

[WebMethod]
public static string[] GetCustomerNames(string searchParam)
{
    List<string> data = new List<string>() { "Andrew", "Ramona", "Russ", "Russell", "Raymond", "Annette", "Anthony" };

    List<string> names = new List<string>();

    foreach (string s in data)
    {
        if (s.ToLower().StartsWith(searchParam))
        {
            names.Add(s);
        }
    }

    return names.ToArray();

}
Was it helpful?

Solution

I was under the impression that you could give a search page as the first parameter to the autocomplete function.

$(document).ready(function(){
  $("#example").autocomplete("Default.aspx/GetCustomerNames", { scroll: false, max: 10, width: 250, selectFirst: true });
});

Something like that, you may need to find out the correct options to use to get it to do what you want, but at least it won't be reinstalling the autocomplete after each keyup.

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