繁体   English   中英

如何基于下拉选择更改jQuery UI自动完成源

[英]How to change jquery ui autocomplete source based on dropdown selection

我是在索引页面上的搜索框中使用jQuery AutoComplete的初学者:

JS:

<script type="text/javascript">
$(document).ready(function () {
    $('#searchName').autocomplete({
        source: '@Url.Action("GetUsers", "Home")'
    });
});
</script>

HTML:

<div id="searchbox" style="float:left;">@Html.TextBox("searchName", null, new { @placeholder = "Name" })

控制器:

      public JsonResult GetUsers(string term)
  {
      Context db = new Context();
      List<string> users;
   .
   .
   .
      return Json(users, JsonRequestBehavior.AllowGet);
  }

目前,“自动完成”功能正在运行,但是我的问题是如何连接一个下拉列表,以将“自动完成”的来源更改为搜索其他用户集的不同功能?

换句话说,我需要根据从下拉列表中选择的值来更改自动完成功能的来源。

这可能吗?

谢谢!

您可以为源选项指定一个函数: http : //api.jqueryui.com/autocomplete/#option-source

使用这种方法,您将更新javascript,以便您可以更好地控制GET调用,因此可以传入第二个参数:

<script type="text/javascript">
$(document).ready(function () {
    $('#searchName').autocomplete({
        source: function (request, response) {
           jQuery.get('@Url.Action("GetUsers", "Home")', {
               term: request.term,
               otherId: $('#otherDdl').val()
           }, function (data) {
               response(data);
           });
        }
    });
});
</script>

然后,在服务器上,您可以检查传入的otherId并基于该更改源。

  public JsonResult GetUsers(string term, int otherId)
  {
      Context db = new Context();
      List<string> users;

      if(otherId == ???)
      // Default search
      else
      // Search alternate location

     .
     .
     .
      return Json(users, JsonRequestBehavior.AllowGet);
  }

自动完成source接受一个回调函数,该函数用于基于下拉值构建数据,例如:

    if(dropdown.val() == 1){
       // hard-coded - get from external source
       var data = [{ "label": "test1", "value": "test1" },
               { "label": "test2", "value": "test2" },
               { "label": "test3", "value": "test3" } ];
    } else{
         ....
    }

然后在自动完成源中将其分配给响应:

source: function (request, response) {
  response(data);                                        
},

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM