【问题标题】:Item not correctly selected with autocomplete未使用自动完成正确选择项目
【发布时间】:2016-04-26 05:50:06
【问题描述】:

我在 Jquery 中有一个带有自动选择功能的文本字段,当您键入三个字母时,您会从数据库中获取一个查询并显示一些数据。我需要从 _renderItem 方法中获取 id 属性,但我没有正确获取它。以下是我的代码:

    $("#textField").autocomplete({
    minLength: 3,
    source: function(request, response) {
        var loadIdentities = "<?php echo $this->Html->url(array('controller' => 'Identities', 'action' => 'getIdentity')); ?>/" + Base64.encode(request.term);
        $.getJSON(loadIdentities, function(data) {
            response(data);
        });
    }
}).data("ui-autocomplete")._renderItem = function(ul, item) {        
     console.log(item.id);
     return $("<li>")           
        .append("<a>" + item.label + "</a>")
            .appendTo(ul);
};

在 console.log(item.id) 行中,我没有得到正确的值。当您使用鼠标单击自动完成列表中的元素时,会发生这种情况,当您单击 item.id 时未正确更新,并且显示的值而不是正确的 item.id 是您在键入时所拥有的值用于自动完成。

例如,如果您在文本字段中输入名称“John Smith”,您将在自动完成功能上看到两个选项:John Smith 和 John Smithson。如果您单击“John Smithson”选项进行选择,您将获得“John Smith”的 item.id 值,而我想要“John Smithson”的 id

我该如何解决这个问题?

【问题讨论】:

    标签: javascript jquery autocomplete jquery-autocomplete


    【解决方案1】:

    我能够使用自动完成的 select 方法解决这个问题:

        select: function( event, ui ) {
                $("[name='elementName[0]']").val(ui.item.label);
                $("[name='elementID[0]']").val(ui.item.id);
                return false;
        }
    

    我把它放在源代码之后,现在它可以工作了。

    【讨论】:

      猜你喜欢
      • 2011-09-05
      • 1970-01-01
      • 2014-09-26
      • 1970-01-01
      • 1970-01-01
      • 2011-08-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多