jquery UI Autocomplete widget select event in web forms

I'm using the jQuery UI Autocomplete inside a .aspx web forms page.
https://jqueryui.com/autocomplete/

I'm using Sql Server 2008 express.
I'm using the Employees table from the Northwind database.

So when I run my page the autocomplete works fine and it looks like this when I start typing in it:

when i start typing in textbox
After I pick Davolio from the autocomplete suggestions I then get this:

after I pick an item from the autocomplete
This is my code for my page

EmployeesByLastName.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="EmployeesByLastName.aspx.cs" Inherits="jquiAutocompleteEvents.EmployeesByLastName" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <link href="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.1/themes/smoothness/jquery-ui.css" rel="stylesheet" type="text/css" />
    <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.1/jquery-ui.min.js"></script>
    <script type="text/javascript">

        $(document).ready(function () {
            //-------------------------

            // ----- jQuery AutoComplete
            $("#txtAutoComplete").autocomplete({
                source: function (request, response) {
                    $.ajax({
                        type: "POST",
                        contentType: "application/json; charset=utf-8",
                        url: "EmployeesByLastName.aspx/GetEmployee",
                        data: "{'term':'" + $("#txtAutoComplete").val() + "'}",
                        dataType: "json",
                        success: function (data) {
                            response(data.d);
                        },
                        select: function (event, ui) {
                            $('#txtAutoComplete').val(ui.item.LastName);
                            $('#selectedValue').text("Selected value:" + ui.item.LastName);
                            return false;
                        },
                        error: function (result) {
                            alert("Error");
                        }
                    });
                }
            });


            //-------------------------
        });

    </script>

</head>
<body>
    <form id="form1" runat="server">
        <div>
            <input type="text" id="txtAutoComplete" />
        </div>
        <div id="selectedValue"></div>
    </form>
</body>
</html>

Open in new window


EmployeesByLastName.aspx.cs

using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Web;
using System.Web.Services;
using System.Web.UI;
using System.Web.UI.WebControls;


namespace jquiAutocompleteEvents
{
    public partial class EmployeesByLastName : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        [WebMethod]
        public static string[] GetEmployee(string term)
        {
            List<string> retCategory = new List<string>();

            string ConnectionString = "Data Source=MyComputer\\SQLEXPRESS;Initial Catalog=Northwind;Integrated Security=True";

            using (SqlConnection con = new SqlConnection(ConnectionString))
            {
                string query = string.Format("select LastName, [LastName] AS value FROM Employees where LastName Like '%{0}%'", term);
                using (SqlCommand cmd = new SqlCommand(query, con))
                {
                    con.Open();
                    SqlDataReader reader = cmd.ExecuteReader();

                    while (reader.Read())
                    {
                        retCategory.Add(reader.GetString(0));
                    }
                }
                con.Close();
            }
            return retCategory.ToArray();
        }

    }
}

Open in new window



On my EmployeesByLastName.aspx page I these divs:

        <div>
            <input type="text" id="txtAutoComplete" />
        </div>
        <div id="selectedValue"></div>

and in the jquery I have this event

                        select: function (event, ui) {
                            $('#txtAutoComplete').val(ui.item.LastName);
                            $('#selectedValue').text("Selected value:" + ui.item.LastName);
                            return false;
                        },


So after I make a selection from the autocomplete the following text should show up on my page below the textbox:

Selected value: Davolio


But for some reason this text is not showing up after I make a selection. So my syntax is wrong somewhere.

Anyone know where my code is wrong?  How do I fix it?
LVL 1
maqskywalkerAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

kblauCommented:
@{
    Layout = null;
}

<!DOCTYPE html>
@*!!!!!!!!!! added to routes routes.IgnoreRoute("{resource}.axd/{*pathInfo}");!!!!!!!*@
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
    <script src="~/Scripts/jquery-1.8.2.min.js"></script>
    <script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
</head>
<body>
    <div>
        <script type="text/javascript">
            var person = {};
            person.ID = $('#txtID').val();
            person.Name = "Amir";

            var pdata = { "p": person };
            var availableTags = [];
            $(document).ready(function () {


                $("#txtAutoComplete").autocomplete({
                    select: AutoCompleteSelectHandler,

                    source: function (request, response) {
                        


                        $.ajax({
                            type: "POST",
                            contentType: "application/json; charset=utf-8",
                            url: "../../SimpleService.asmx/GetAP",
                            data: JSON.stringify(pdata),
                            dataType: "json",
                            async: true,
                            success: function (data, textStatus) {
                                //if (textStatus == "success") {
                                //    if (data.hasOwnProperty('d')) {
                                //        availableTags = data.d;
                                //        $("#tags").autocomplete({ source: availableTags });
                                //    } else {
                                //        msg = data;
                                //    }
                                //}
                                response(data.d);


                            },

                            



                            error: function (data, status, error) {
                                alert("error");
                            }
                        });

                    }
                });
            });

            function AutoCompleteSelectHandler(event, ui) {
                var selectedObj = ui.item;
                alert(selectedObj.value);
            }
        </script>
    </div>



    <div>
        <input type="text" id="txtAutoComplete" />
    </div>
    <div id="selectedValue"></div>

</body>
</html>

Open in new window


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;

namespace MvcApplication8
{
    /// <summary>
    /// Summary description for SimpleService
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    [System.Web.Script.Services.ScriptService]
    public class SimpleService : System.Web.Services.WebService
    {

        [WebMethod]
        public string[] GetAP(Person p)
        {
            string[] s = { "ap1gh", "ap2gh", "ap3gh" };
            return s;
        }
    }
}

Open in new window


You need to add to register routes if you are using mvc

routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

Open in new window

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
jQuery

From novice to tech pro — start learning today.