My autocompelete firing too many times
I am using the autocomplete here: http://blog.idealmind.com.br/geral/simple-autocomplete-jquery-plugin/
It has two problems:
1) It doesn't work the first time something is entered into textbox - not such a big problem, as you don't really want to match a single letter 2) The more irritating thing is that it fires too many times.
My javascript is here:
<script type="text/javascript">
function nameAutocomplete(field){
alert($(field).val());
$("#name").simpleAutoComplete(
'Ajax.action',
{ 'input': $(field).val(),
'_eventName': 'getObjectsByAjax'
},
function(data){
alert("we're in business");
}
);
}
</script>
The HTML looks like this:
<input type="text" name="name" id="name" size="45" class="medium-text" onkeyup="nameAutocomplete(this);"/>
This is the part of the plugin (below) that makes the Ajax call (which is working fine):
$.get(page,
{ 'input': thisElement.val(),
'_eventName': 'getObjectsByAjax'
},
function(res)
{
$('div.' + classAC).remove();
$("#autocomplete_tooltip").remove();
var r="";
var respObject=eval(res);
r+="<ul>";
for(var i in respObject)
{
r+='<li id="autocomplete_'+respObject[i].id+'"><table cellspacing=0 width="100%"><tr><td class="icon" width="20" uri="'+respObject[i].uri+'"><a href="/sempedia/Resource.action?id='+respObject[i].id+'" ><img src="images/green-file.png"></a></td><td class="caption">'+respObject[i].name+"</td></tr></table></li>";
}
r+="</ul>";
autoCompleteList = $('<div>').addClass(classAC).html(r);
I have printed the entire plugin code here:
(function($){
$.fn.extend(
{
simpleAutoComplete: function( page, options, callback ) {
if(typeof(page) == "undefined" ) {
alert("simpleAutoComplete: Você deve especificar a página que processará a consulta.");
}
var classAC = 'autocomplete';
var selClass = 'sel';
var attrCB = 'rel';
var thisElement = $(this);
$(":not(div." + classAC + ")").click(function(){
$("div." + classAC).remove();
$("#autocomplete_tooltip").remove();
});
thisElement.attr("autocomplete","off");
thisElement.keyup(function( ev )
{ var getOptions = { input: thisElement.val() }
if( typeof(options) == "object" )
{
开发者_Go百科 classAC = typeof( options.autoCompleteClassName ) != "undefined" ? options.autoCompleteClassName : classAC;
selClass = typeof( options.selectedClassName ) != "undefined" ? options.selectedClassName : selClass;
attrCB = typeof( options.attrCallBack ) != "undefined" ? options.attrCallBack : attrCB;
if( typeof( options.identifier ) == "string" )
getOptions.identifier = options.identifier;
if( typeof( options.extraParamFromInput ) != "undefined" )
getOptions.extraParam = $( options.extraParamFromInput ).val();
}
kc = ( ( typeof( ev.charCode ) == 'undefined' || ev.charCode === 0 ) ? ev.keyCode : ev.charCode );
key = String.fromCharCode(kc);
console.log(kc, key, ev );
if (kc == 27)
{
$('div.' + classAC).remove();
$("#autocomplete_tooltip").remove();
}
if (kc == 13)
{
$('div.' + classAC + ' li.' + selClass).find(".caption").trigger('click');
}
if (key.match(/[a-zA-Z0-9_\- ]/) || kc == 8 || kc == 46)
{
$.get(page,
{ 'input': thisElement.val(),
'_eventName': 'getObjectsByAjax'
},
function(res)
{
$('div.' + classAC).remove();
$("#autocomplete_tooltip").remove();
var r="";
var respObject=eval(res);
r+="<ul>";
for(var i in respObject)
{
r+='<li id="autocomplete_'+respObject[i].id+'"><table cellspacing=0 width="100%"><tr><td class="icon" width="20" uri="'+respObject[i].uri+'"><a href="/sempedia/Resource.action?id='+respObject[i].id+'" ><img src="images/green-file.png"></a></td><td class="caption">'+respObject[i].name+"</td></tr></table></li>";
}
r+="</ul>";
autoCompleteList = $('<div>').addClass(classAC).html(r);
if (r != '')
{
autoCompleteList.insertAfter(thisElement);
var position = thisElement.position();
var height = thisElement.height();
var width = thisElement.width();
$('div.' + classAC).css({
'top': ( height + position.top + 6 ) + 'px',
'left': ( position.left )+'px',
'margin': '0px'
});
$('div.' + classAC + ' ul').css({
'margin-left': '0px'
});
$('div.' + classAC + ' li').each(function( n, el )
{
el = $(el);
el.mouseenter(function(){
$('div.' + classAC + ' li.' + selClass).removeClass(selClass);
$(this).addClass(selClass);
});
el.find(".caption").click(function()
{
thisElement.attr('value', el.text());
if( typeof( callback ) == "function" )
callback( el.attr(attrCB).split('_') );
$('div.' + classAC).remove();
thisElement.focus();
});
el.hover(function(e) {
urlText=$("<div>").attr("id","autocomplete_tooltip").addClass("tooltip").html($(this).find("td").attr("uri"));
urlText.css({
position:"absolute",
top:(e.pageY+20)+"px",
left:(e.pageX+20)+"px"
});
$("body").append(urlText);
},function() {
$("#autocomplete_tooltip").remove();
});
});
}
});
}
if (kc == 38 || kc == 40){
if ($('div.' + classAC + ' li.' + selClass).length == 0)
{
if (kc == 38)
{
$($('div.' + classAC + ' li')[$('div.' + classAC + ' li').length - 1]).addClass(selClass);
} else {
$($('div.' + classAC + ' li')[0]).addClass(selClass);
}
}
else
{
sel = false;
$('div.' + classAC + ' li').each(function(n, el)
{
el = $(el);
if ( !sel && el.hasClass(selClass) )
{
el.removeClass(selClass);
$($('div.' + classAC + ' li')[(kc == 38 ? (n - 1) : (n + 1))]).addClass(selClass);
sel = true;
}
});
}
}
if (thisElement.val() == '') {
$('div.' + classAC).remove();
$("#autocomplete_tooltip").remove();
}
});
}
});
})(jQuery);
Pull the part that does the ajax call into a function, and then "debounce" it like this:
var timeout = thisElement.data('timeout');
function debouncedAjax() {
if (timeout) {
clearTimeout(timeout);
}
timeout = setTimeout(ajax, 500);
thisElement.data('timeout', timeout);
}
That way you'll be able to call debouncedAjax
everywhere it now calls ajax
and it will only do one call after a lull of 500ms. Adjust the timeout to taste.
I ended up using a global variable to store the setTimeout() with a call for the Ajax Function and every time a keyup happens you clear this variable and reset it with the new Ajax call, like this:
$(document).ready(function () {
// Define the global variable
$.go = null;
// Element keyup
$("#YourElementId").keyup(function() {
// Clear the global variable with the previous Ajax
clearTimeout($.go);
// Set the variable with the current Ajax call
$.go = setTimeout(function() {
FunctionThatCallsTheAjax();
},1000);
});
});
function FunctionThatCallsTheAjax(){
// Ajax Stuff Here
}
You can adjust the '1000' timeout. It's working nice for me.
精彩评论