找到上面的答案,但它有来自 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;
}
}
}
});