[英]Can't get autocomplete to work on first keypress
I managed to get my search bar to accept a parameter for my API call. 我设法使搜索栏接受API调用的参数。 My only problem is that the search bar does not work on the first keypress.
我唯一的问题是搜索栏在第一次按键时不起作用。 It will work on the second keypress.
它将在第二个按键上工作。 I have looked at this answer that told me to try and remove the
onkeyup
but that has not worked for me. 我看过这个回答,告诉我尝试删除
onkeyup
但对我没有用。
This is my HTML 这是我的HTML
<html>
<div class="card-header">Search</div>
<div class="card-body">
<div class="autocomplete">
<input id="searchBar" class="form-control mdb-autocomplete" type="text" placeholder="Enter Name" onkeyup="nameSearch()">
</div>
</div>
And my Javascript 还有我的Javascript
<script>
function nameSearch(){
var name = $('#searchBar')[0].value;
$("#searchBar").autocomplete({
delay:100,
source: function(request ,response){
$.ajax({
type: 'GET',
url: APIURL,
datatype: 'json',
data: {
term : request.term,
'symbol':name
},
success: function(list){
if(list.length !== 0)
response(list);
else{
alert("Name does not exist");
}
}
});
},
});
}
</script>
As was mentioned in the linked post, executing all that in the key handler is too late. 如链接文章中所述,在密钥处理程序中执行所有操作为时已晚。 That's not how Autocomplete was designed.
这不是自动完成设计的方式。 Consider the following.
考虑以下。
$(function() { $("#searchBar").autocomplete({ delay: 100, source: function(request, response) { $.ajax({ type: 'GET', url: APIURL, datatype: 'json', data: { term: request.term, symbol: request.term }, success: function(list) { if (list.length !== 0) response(list); else { alert("Name does not exist"); } } }); }, }); });
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"> <script src="https://code.jquery.com/jquery-1.12.4.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> <div class="card-header">Search</div> <div class="card-body"> <div class="autocomplete"> <input id="searchBar" class="form-control mdb-autocomplete" type="text" placeholder="Enter Name"> </div> </div>
This initializes the Autocomplete when the page is ready. 页面准备就绪时,这将初始化自动完成功能。 When the User enters a keystroke, then it is run, the default min length is
1
. 当用户输入击键时,它将被运行,默认的最小长度是
1
。 Remember if this is a larger record set, you may want to alert the user that a search is happening or adjust the min length to something like 3
. 请记住,如果这是一个较大的记录集,则可能要提醒用户正在搜索,或将最小长度调整为
3
。
The minimum number of characters a user must type before a search is performed.
用户在执行搜索之前必须键入的最少字符数。 Zero is useful for local data with just a few items, but a higher value should be used when a single character search could match a few thousand items.
零对于仅包含少量项目的本地数据很有用,但是当单个字符搜索可以匹配数千个项目时,应使用更高的值。
Hope that helps. 希望能有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.