我有一個輸入字段有一個附加到它的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