There are situations where you want to apply autocomplete on two different input boxes.
Below is the code which does exactly the same.
Construct your Html:
<input type="text" id="txtPartNum" class="autosuggest" />
<input type="text" id="txtPartNum2" class="autosuggest" />
Javascript:
// load js libraries from CDN.
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/jquery-ui.min.js"></script>
<script type="text/javascript">
// on load of page, invoke SearchText() function.
//which will apply autocomplete on input boxes with class "
autosuggest
".
$(document).ready(function () {
SearchText();
});
// Function finds all input boxes with class "autosuggest" and applies autocomplete on it. function SearchText() {
$(".autosuggest").autocomplete({
select:function(event, ui){
window.location.href = '/Products/ProductInfoCenter.aspx?partnum=' + ui.item.value;
},
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "/test.aspx/GetAutoCompleteData",
data: "{'PartNumber':'" + $(this.element).val() + "'}",
dataType: "json",
success: function (data) {
response(data.d);
},
error: function (result) {
alert(err.message);
}
});
}
});
}
</script>
//Server side i am using C# as below: it returns JSON data as response.
[WebMethod]
public static List<string> GetAutoCompleteData(string term)
{
List<string> result = new List<string>();
OdbcConnection conn = new OdbcConnection(DB.DatabaseConnString());
string query = "SELECT * from gallery WHERE (unique_no LIKE '%" + NJS_Helper.FormatStringforDB(term) + "%') limit 5;";
if (conn.State == ConnectionState.Open)
conn.Close();
conn.Open();
OdbcDataReader dataReader = new OdbcCommand(query, conn).ExecuteReader();
if ((dataReader != null) && (dataReader.HasRows))
{
while (dataReader.Read())
{
result.Add(dataReader["unique_no"].ToString());
}
}
dataReader.Close();
return result;
}
No comments:
Post a Comment