jquery自动填充自动填充字段,带有第一个值和高亮度添加部分

即时通讯使用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)来编辑样式,但仍然不是我想要的..

不幸的是,它没有现成的选择。 幸运的是,使用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 } } }); 

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

您需要自己编写代码或查看是否有不同的自动完成插件执行此操作。

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

找到上面的答案,但它有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