【问题标题】:Jquery autocomplete on select event选择事件上的Jquery自动完成
【发布时间】:2012-09-25 05:32:32
【问题描述】:

我正在使用 jQuery 自动完成功能,它工作正常,现在我想在发生以下情况时从 jQuery 的会话中存储一个变量。

当有人键入任何单词时,jQuery 会显示建议下拉列表,如果有人从该建议下拉列表中选择一个项目。

我想捕获上述点并在会话中存储一个变量。

我搜索了 Google、StackOverflow,但没有找到相关的解决方案。我的自动完成代码如下:

  $(".autosearch-smart").autocomplete('Home/GetCompanyNames', {
    minChars: 1,
    width: 402,
    matchContains: "word",
    autoFill: true
});

这就是我尝试做的:

  $(".autosearch-smart").autocomplete('Home/GetCompanyNames', {
    minChars: 1,
    width: 402,
    matchContains: "word",
    autoFill: true,
    select: function (a, b) {
        alert("selected");
    }

});

编辑:选择事件处理程序也不起作用

我正在使用带有 C# 的 asp.net MVC3。请帮助我并提前感谢。

【问题讨论】:

  • 检查你的错误控制台它说什么...?
  • 控制台@Anant没有显示
  • @smartboy 你用过哪些jquery库??
  • 我发布了一些关于自动完成的问题。你能检查一下并说一下有什么问题吗。stackoverflow.com/questions/36860915/…

标签: javascript jquery asp.net-mvc jquery-ui jquery-ui-autocomplete


【解决方案1】:

因此,如果我理解正确,您希望将所选值存储在变量会话中

您可以通过以下代码从所选项目中获取值:

  $(".autosearch-smart").autocomplete('Home/GetCompanyNames', {
minChars: 1,
width: 402,
matchContains: "word",
autoFill: true,
select: function (event, ui) {
    var label = ui.item.label;
    var value = ui.item.value;
   //store in session
  document.valueSelectedForAutocomplete = value 
}
});

值和标签是来自服务器的json对象

希望对你有帮助

【讨论】:

  • Select 事件不起作用,正如我在问题中告诉你的那样,我再次尝试但没有成功
【解决方案2】:

好吧,如果你想使用 asp.net mvc3 存储在会话中,那么请执行以下操作

$(".autosearch-smart").autocomplete('Home/GetCompanyNames', {
    minChars: 1,
    width: 402,
    matchContains: "word",
    autoFill: true,
    select: function (event, ui) {   //must be cleared with function parameter
        //alert(ui.item.label);  //will show you the selected item

       $.ajax({
          type: 'POST',
          url: '/Controller/Action1',  //whatever any url
          data: {label: ui.item.label},
          success: function(message) { if(message.data == true) ... else ... },
          dataType: 'json'
       });

    }

});

和控制器

[HttpPost]
  public JsonResult Action1( string label ) {

     this.Session["AnyValue"] = label;

     return Json( new {
        data = true
     }, JsonRequestBehavior.AllowGet );
  }

【讨论】:

  • 不要认为你需要 JsonRequestBehavior.AllowGet 设置,因为它被过滤为 HTTPPOST
  • 是可选的 (JsonRequestBehavior.AllowGet)
猜你喜欢
  • 2011-12-05
  • 2014-11-19
  • 2017-02-16
  • 2018-10-11
  • 2011-05-13
  • 2011-04-06
  • 1970-01-01
  • 2014-05-09
  • 1970-01-01
相关资源
最近更新 更多