我知道以下相同的问题:Always show a specific choice in jQuery Autocomplete even if it doesn't match input
问题是,如上述问题中建议的那样使用开放功能作为解决方案时,仅当自动完成列表中有匹配项时才触发事件。因此,当用户在搜索框中键入内容时,并不总是显示特定的选择。
https://jsfiddle.net/u1jwz6s4/
<html lang="en">
<head>
<meta charset="utf-8">
<title>autocomplete demo</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.12.4.js"></script>
<script src="//code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>
<body>
<label for="autocomplete">Select a programming language: </label>
<input id="autocomplete">
</body>
</html>
$( "#autocomplete" ).autocomplete({
source: [ "c++", "java", "php", "coldfusion", "javascript", "asp", "ruby" ],
open: function(){
$('.ui-autocomplete').prepend("search by keyword")
},
});
无论用户在搜索框中键入内容时是否有匹配的字符串,我都希望始终在最上方显示“作为关键字搜索”。当前,仅当找到匹配的字符串时,“搜索为关键字”才显示在顶部。另外,是否有使“搜索为关键字”成为搜索表单中可点击事件的方式?看到jsfiddle看看我在描述什么。
答案 0 :(得分:2)
您可以使用response选项将unshift
字符串search by keyword
移至显示的标签数组:
const $input = $("#autocomplete");
$input.autocomplete({
source: ["c++", "java", "php", "coldfusion", "javascript", "asp", "ruby"],
response: (event, ui) => {
const label = 'search by keyword';
ui.content.unshift({
label,
value: $input.val()
});
}
});
$(document).on('click', '.ui-autocomplete div:contains("search by keyword")', () => {
console.log('searching for ' + $input.val());
});
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.12.4.js"></script>
<script src="//code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<label for="autocomplete">Select a programming language: </label>
<input id="autocomplete">