Tuesday, 15 July 2014

Autocomplete with two input boxes- jquery

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" />

// 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 () {
   // Function finds all input boxes with class "autosuggest" and applies autocomplete on it.
  function SearchText() {
       select:function(event, ui){
       window.location.href = '/Products/ProductInfoCenter.aspx?partnum=' + ui.item.value;
      source: function (request, response) { 
            type: "POST",
            contentType: "application/json; charset=utf-8",
            url: "/test.aspx/GetAutoCompleteData",
            data: "{'PartNumber':'" + $(this.element).val() + "'}",
            dataType: "json",
            success: function (data) {
            error: function (result) {
    //Server side i am using C# as below: it returns JSON data as response.
    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)
            OdbcDataReader dataReader = new OdbcCommand(query, conn).ExecuteReader();
            if ((dataReader != null) && (dataReader.HasRows))
                while (dataReader.Read())
          return result;

No comments:

Post a Comment