I have an ASP.NET 4.5 WebForm app where I want to add autocomplete to a TextBox. I was looking into jquery-ui but I can't seem to make it work.
I'm using jquery 3.1.1 and jquery-ui 1.12.1. Here is the head part of my aspx page.
ASPX
<head runat="server">
<link href="//ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#SearchDynamicTxt").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "UserReports.aspx/GetUsers",
data: "{'term':'" + $("#SearchDynamicTxt").val() + "'}",
dataType: "json",
success: function (data) {
response(data.d);
},
error: function (result) {
alert("Error");
}
});
}
});
});
</script>
</head>
Here is the text control:
<asp:TextBox ID="SearchDynamicTxt" runat="server" OnTextChanged="SearchDynamicTxt_TextChanged" AutoPostBack="true" ></asp:TextBox>
Here is the code behind:
[WebMethod]
public static string[] GetUsers(string term)
{
List<string> usersList= new List<string>();
string CS= ConfigurationManager.ConnectionStrings["UsersCS"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
con.Open();
SqlCommand cmd = new SqlCommand("SELECT Name FROM Customers WHERE Name Like '" + term + "%'", con);
SqlDataReader reader = cmd.ExecuteReader();
while(reader.Read())
{
usersList.Add(reader[0].ToString());
}
}
return usersList.ToArray();
}
I'm sure there is something that I forgot or misspelled but I don't know what or where. When I try writing something in the control, nothing happens. I would like it to show me a list of possible matching users and when I select one of them, to call the method OnTextChanged.
Update
Now that the dropdownlist shows up, I want to select an user and that selection to trigger the OnChanged method. Currently this is not happening. I need to press enter or click somewhere on the page to generate a postback and then it detects the OnChanged text. I'm guessing that I need to change this:
success: function (data)
{
response(data.d);
},
Perhaps adding an event parameter or something?