【问题标题】:Make autocomplete work on a dropdown and have it fill contents of another dropdown使自动完成在下拉列表上工作并让它填充另一个下拉列表的内容
【发布时间】:2014-02-14 06:48:59
【问题描述】:

由于回发问题,我正试图摆脱服务器端控制。我想要两个从数据库中填充的选择框。当页面加载时,我将拥有一个已经从数据库中预填充的组合框:

<select ID="cboCustomers">
   <option value="0">--Select a Sold-to customer--</option>
   <option value="1">Customer1</option>
   <option value="2">Customer2</option>
   <option value="3">Customer3</option>
   <option value="4">Customer4</option>
</select>

<select ID="cboShipTo">
   <option value="0">--Select a Ship-to customer--</option>
</select>

The first dropdown should have autocomplete enabled and when a value is selected, it should use AJAX to populate the second drop down list with Ship-to customers that are available for the selected Sold-to customers.我有一个对象,它将接受参数并返回适当的数据。我的问题是如何完成上述任务。您能否提供一些示例代码或 jsFiddle 来满足我的要求?提前感谢您的帮助!

【问题讨论】:

    标签: javascript jquery html asp.net ajax


    【解决方案1】:

    我遇到了同样的问题,但是在网上找了一些资源。

    先做ajax语句:

    jQuery

    $('#cboCustomers').onchange(function(){
     var $valueTofound = $(this).val();
     $.ajax({
     type: "POST",
     url: "Your URL",
     data: Json.stringify({valueTofound : $valueTofound }), //You will pass data to code behind
     contentType: "application/json; charset=utf-8",
     dataType: "json",
     success: function (data) {
     $.each(jQuery.parseJSON(data.d), function () {
            $("#ddlRecords").append($("<option>  </option>").val(this['ID']).html(this['Name'])); //fill the dropdown
     });
     },
     error: function (msg) {
     //error
     }
     });
    });
    });
    

    C# 背后的代码

    [WebMethod]
         public static string GetResultset(string valueTofound)
         {
           DataTable dataTable = new System.Data.DataTable(); //create a DataTable
           using (SqlConnection sqlConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString))
         {
          try
          {
           SqlDataAdapter sqlDataAdapter = new SqlDataAdapter("DO your Select", sqlConnection);
           sqlDataAdapter.Fill(dataTable);  //Fill the Datatable
           return JsonConvert.SerializeObject(dataTable); //return to Jquery
          }
          catch (Exception ex)
          {
           throw ex;
          }
       }
    }
    

    这将对您有所帮助,或者您还有其他页面:

    How to fill Dropdown from c# Other page

    【讨论】:

    • 谢谢@freak_droid,但是在第一个下拉菜单中键入时自动完成/自动查找呢?
    • @MichaelMahony 我认为是一样的,因为当您的类型或更改选项时会触发 onchange 事件,在我的情况下,我使用了 whitout auntocomplete,但我很确定是相同的方式。
    • 我的错误是keyup或keypress
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-13
    • 2018-02-03
    • 2014-09-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多