我有一个输入字段有一个附加到它的ajax数据源自动完成。如何用jqueryui取消自动填充?
我有一个输入字段,看起来有人按enter当他们这样做它触发搜索按钮,它的ajax加载在另一个DIV一些数据点击一个KEYUP处理程序。
问题是,如果人很快并键入并按下输入,自动完成仍会弹出。
我曾尝试以下:
添加
$('#autocomplete').autocomplete('close')
。这不起作用,可能是因为自动完成功能尚未打开。如果我输入,等待自动填充出现,然后按回车,它会正确关闭它。添加
$('#autocomplete').autocomplete('destroy')
。这是有效的,但如果我回到现场尝试其他搜索,自动完成功能将不再有效。
所以,我要的是取消所有待处理的请求,并关闭自动完成,如果它是开放的,但没有禁用或摧毁它的方式。编辑:代码示例(不是我真实的代码,只是存根,以演示问题)。文件名是scratch.php
<?php
// Stub for search results
if ($_GET['search'])
{
print "Search results for ".$_GET['search']." here";
exit();
}
// Simulated DB search
if ($_GET['term'])
{
print '[{"label":"A 1"},{"label":"A 2"},{"label":"A 3"},{"label":"A 4"}]';
exit();
}
?>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://code.jquery.com/ui/1.10.1/jquery-ui.js"></script>
<link type="text/css" href="http://code.jquery.com/ui/1.10.1/themes/redmond/jquery-ui.css" rel="stylesheet" />
<script language='javascript'>
$(document).ready(function() {
$('#searchfor').on('keyup',function(e) {
if (e.which == 13) $('#search').trigger('click');
});
$('#searchfor').autocomplete({
source: "/scratch.php",
minLength: 2,
select: function(event, ui) {
$('#searchfor').val(ui.item.value);
$('#search').trigger('click');
}
});
$('#search').on('click',function() {
try
{
// Cancel any pending autocompletes without destroying the autocomplete completely here.
// This currently doesn't work
$('#searchfor').autocomplete("close");
}
catch(e)
{
// Do nothing except prevent an error
}
$('#results').load('scratch?search='+encodeURIComponent($('#searchfor').val()));
});
});
</script>
</head>
<input id='searchfor' /> <input id='search' type='button' value='search' />
<div id='results'></div>
</html>
请提供的代码和/或[的jsfiddle](HTTP ://jsfiddle.net)示例 – Dom 2013-03-25 20:08:36
@Dom - 添加了代码片段。我不确定如何用jsfiddle模拟服务器端的东西,所以我只是粘贴了一个简化的代码片段来展示手头的问题。 – 2013-03-25 21:00:40
增加延迟和使用禁用方法,而不是密切的方法呢? – jmm 2013-03-25 21:50:59