10

我使用带有以下代码的 jqueryui 自动完成插件

$(this).autocomplete({
                source: function(request, response) {
                    $.ajax({ url: 'clinic/auto',
                    data: { 'term': this.term,'name': this.element.attr('complete')},
                    dataType: "json",
                    type: "POST",
                    success: function(data){
                        response(data);
                    }
                });
            },
            minLength: 2
        });

这会在下拉列表中显示所有结果的列表。

我的问题是如何让它为你自动完成工作并突出显示添加的部分以便于使用?

我必须编码吗?或者有一个已经存在的选项?如果我手动做它怎么做?示例图片: 在此处输入图像描述

到目前为止的解决方案:

我发现这个链接 ,这对编辑样式非常有用(猴子补丁 jquery-autocomplete),但仍然不是我想要的..

4

4 回答 4

19

不幸的是,它没有现有的选项。幸运的是,使用 JQuery Autocomplete 提供的事件有一种非常简单的方法。看看这个 JSFiddle:http: //jsfiddle.net/RyTuV/133/

您会注意到,您要添加的相关代码使用JQuery Autocomplete Open 事件

当建议菜单打开或更新时触发。

使用此事件,您可以将列表中第一项的文本添加到已输入到输入字段中的内容中,然后从输入文本之后突出显示到添加文本的末尾:

$(this).autocomplete({
    source: function(request, response) {
                $.ajax({ url: 'clinic/auto',
                data: { 'term': this.term,'name': this.element.attr('complete')},
                dataType: "json",
                type: "POST",
                success: function(data){
                    response(data);
                }
            });
    },
    minLength: 2,
    open: function( event, ui ) {
        var firstElement = $(this).data("autocomplete").menu.element[0].children[0]
           , inpt = $('#autocomplete')
           , original = inpt.val()
           , firstElementText = $(firstElement).text();

        /*
           here we want to make sure that we're not matching something that doesn't start
           with what was typed in 
        */
        if(firstElementText.toLowerCase().indexOf(original.toLowerCase()) === 0){
            inpt.val(firstElementText);//change the input to the first match

            inpt[0].selectionStart = original.length; //highlight from end of input
            inpt[0].selectionEnd = firstElementText.length;//highlight to the end
        }
    }
});

使用它作为模板,您可以遍历菜单中的项目以找到以输入文本开头的第一个匹配项,并使用它来填充和突出显示,而不是仅使用第一项。

于 2013-06-18T04:22:51.430 回答
2

您需要自己编写代码或查看是否有其他自动完成插件可以执行此操作。

要自己编写代码,您需要引用response事件以获取第一个匹配的结果文本并将其放入输入框中。要操作选定的文本,请参阅这篇文章:使用 jQuery 在输入框中选择部分字符串

于 2012-12-28T00:05:01.320 回答
0

找到上面的答案,但它有来自 jqueryUI 的下拉列表,所以我开始编写自己的脚本。并决定在这里发布。工作jsfiddle:https ://jsfiddle.net/wb3kpxaj/

代码:

/* Need jquery to be extended with code snippet for selectrange i found somewhere, but forgot where...: */
$.fn.selectRange = function(start, end) {
  var e = document.getElementById($(this).attr('id')); // I don't know why... but $(this) don't want to work today :-/
  if (!e) return;
  else if (e.setSelectionRange) { e.focus(); e.setSelectionRange(start, end); } /* WebKit */ 
  else if (e.createTextRange) { var range = e.createTextRange(); range.collapse(true); range.moveEnd('character', end); range.moveStart('character', start); range.select(); } /* IE */
  else if (e.selectionStart) { e.selectionStart = start; e.selectionEnd = end; }
  return $(e); };

autofill=['Banana', 'Banonas', 'Appel', 'Appelpie', 'Other', 'OtherMoreSpecific', 'OtherMoreDifferent'];

$('#autofill').on('keyup', function(e) {
   unvalidInputKeys=[8,9,13,16,17,18,19,20,27,33,34,35,36,37,38,39,40,45,46,91,92,93,112,113,114,115,116,117,118,119,120,121,122,123,144,145];
  if($(this).val().length>0&&!unvalidInputKeys.includes(e.keyCode)) {
    for(i=0;i<autofill.length;i++) {
      if(autofill[i].startsWith($(this).val())) {
        userTypedLength=$(this).val().length;
        $(this).val(autofill[i]);
        $(this).selectRange(userTypedLength, autofill[i].length);
        return;
        }
      }
    }
  });
于 2017-07-03T15:04:02.040 回答
0

Works great! On mobile devices: not so much though. The first item from the menu gets selected automatically after it shows up for the first time.

To avoid this, I came up with this solution for mobile devices:

    close: function( event, ui ) {
        let firstElement =  $(this).data("uiAutocomplete").menu.element[0].children[0]
           , inpt = $(this)
           , original = inpt.val()
           , firstElementText = $(firstElement).text();

        /*
           here we want to make sure that we're not matching something that doesn't start
           with what was typed in 
        */
        if(firstElementText.toLowerCase().indexOf(original.toLowerCase()) === 0){
            inpt.val(firstElementText);//change the input to the first match

            inpt[0].selectionStart = original.length; //highlight from end of input
            inpt[0].selectionEnd = firstElementText.length; //highlight to the end
            $("#zoominmap").click(); // trigger click on mobile
        }
    },

close instead open - and a click event on a button (#zoominmap) after the highlighting.

I have the whole code wrapped in this media query btw:

if (window.matchMedia('only screen
 and (min-device-width:120px)
 and (max-device-width:767px)').matches) {
/*
mobile
*/
} else {
/*
desktop
*/
}
于 2018-11-20T19:24:54.480 回答