Hello, I'm currently struggling with getting the values of the text inputs from autocompletes to use in other portions of the page. I think it might be a scope thing, but I'm not solid on jquery, so I don't know how changing something in one place might break the script to begin with.
What I want to be able to do is to start typing in a company name, have it autocomplete, and then later when I click a button, I want the contents of that textbox to populate a label somewhere else. I also want to be able to run a query with that data to place into a data table, however, I think the solution to one will be the solution to the other.
What's happening now is that I cannot access anything from within the public static list, as everything beyond it appears to be in an outer scope, so assuming there's even a value assigned to the textbox, I can't reach it anyways.
Here's a list of the files in play:
- svcfunctions.js
- servicehub.aspx
- servicehub.apsx.cs
Starting with the snippet from the aspx:
</div> <div class="large-4 columns">
<label>Company:</label>
<div class="demo">
<div class="ui-widget">
<input type="text" id="txtSearch" class="autosuggest"/>
</div>
</div>
</div>
Here's the snippet from the aspx.cs (code-behind):
[WebMethod]
public static List<string> GetAutoCompleteData(string companyname)
{
List<string> result = new List<string>();
using (SqlConnection con = new SqlConnection("Data Source=DATAX;Integrated Security=true;Initial Catalog=Archive"))
{
using (SqlCommand cmd = new SqlCommand("SELECT DISTINCT CardName from [Archive].[dbo].[Customers] WHERE CardName LIKE @SearchText+'%'", con))
{
con.Open();
cmd.Parameters.AddWithValue("@SearchText", companyname);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
result.Add(dr["CardName"].ToString());
}
return result;
}
}
}
Here's the snippet from the js:
$(document).ready(function () {
SearchText();
});
function SearchText() {
$(".autosuggest").autocomplete({
minLength: 3,
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "ServiceHub.aspx/GetAutoCompleteData",
data: "{'companyname':'" + document.getElementById('txtSearch').value + "'}",
dataType: "json",
success: function (data) {
response(data.d);
},
error: function (result) {
alert("Error: Invalid SQL Query in AutoComplete (CardName)");
}
});
}
});
}
The autocomplete works fine, but I can't access the selected or held value sitting in the text box.