Autocomplete

8 Апрель 2008

Prehistory


First of all, I want to say, that this plugin was developed for KyivStar, therefore all fine details were studied and stipulated very carefully. For example, what should occur, when the user would reach last element of the list: whether it should rest against the end or begin a cycle all over again. Or whether the list should disappear when the cursor is out of it. All this passed through business analysts’ and designer and only then came to me.

On the other hand I tried to make autocomplete multifunctional (multipurpose) and as simple as possible for any person to use it on ones site. Remarkable is that even with switched off javascript the site would not lose functionality, and visitor can enter data anyway. Autocomplete was not made as a filtrator of data entered by the user but the tool which helps the user to fill the form more quickly.

Well-known plugin jquery.suggest was taken as an example. Pieces of which can be identified in some methods. In spite of the fact that I took mechanism, I have added some new functions and have removed some errors. So in last version jquery.suggest the code became more readable thanks to the removal of one check. But at the end of the list the cursor (illumination) disappears for one position and then again appears at the first element of the list. It happens because jquery (in traversing) always return itself to the object and doesn’t give value to quantity chosen nodes. Another authors fault that he persistently tries to apply $.fn.bgiframe to the list <ul/>, This invention is certainly noble, but I couldn’t deal with this on practice.

Functions that were added: generation of the list from select-box, the limited visible part of the list with scrolling and prefilling of the list for it to look like a select-box. One more events handling onKeyPress. Well-known algorithm of caching MRU was deleted and replaced with my cache algorithm, this takes a lot of memory but it very fast!



Downloads


Last update 14.09.2009!


HTML file with examples (autocomplete.html)
Plugin itself (jquery.autocomplete.js)
Styles (autocomplete.css)
Little blue arrow (select.gif)
Progress bar backgraund image (progress.gif)
Php backend (search.phps)

Copy all this files to your own local web-server in root directory, rename search.phps to search.php and run http://path.to.your.server/autocomplete.html.



Examples


Example 1: Minimal requirements

To launch plugin you just need to put in one parameter, the url of php script which generats a list of words. Format of the list can be either xml or json.


$("#autocomplete1").autocomplete({
	url:'search.php'
});

Example 2: onSelect event

Plugin has four public events. First of them is onSelect, it fires where you pick element from the list. You can activate it by left clicking or pressing 'enter' button on the selected item. In this example I use one second delay before searching, and string must be at least 2 characters. The ansver from server will be in xml format so you can omit type property.


$("#autocomplete2").autocomplete({
	url:'search.php?type=xml',
	minchar:2,
	delay:1000, // in milliseconds
	onSelect:function(){
		alert(this.ac.val())
	},
	type:'xml'
});

Example 3: onKeyPress

onKeyPress event fires when you are typing. It can be used to filtrate user input. In this example you can use only alphabetical characters and white space, all other characters will be deleted. The fillin flag will fill in list before user start typing, because of input string is empty the request to the server will also contains empty mask value (i.e. search.php?type=json&mask=). In this case you will see list of one item with text "The list is empty!". The ansver from server will be in json format and you must set type property to 'json'.


$("#autocomplete3").autocomplete({
	url:'search.php?type=json',
	onKeyPress:function(){
		var o=this;
		setTimeout(function(){
			o.ac.val(o.ac.val().replace(/[^a-z ]+/g,""))
		},50)
	},
	fillin:true,
	type:'json'
});

Example 4: onError event

onError and onSuccess is the last two events, onError fires when AJAX has a problems otherwise onSuccess fires when you get answer from server. For example onError fires where you request for non-existing page. Also its an example of how to disable autocomplete. onSuccess get the same parametrs and scope.


$("#autocomplete4").autocomplete({
	url:'non_exist.php',
	onError:function(XMLHttpRequest, textStatus, errorThrown){
		this.ac.val(textStatus);
		this.ac.attr({disabled:"disabled"}).css({'background-color':'#d0d0d0'});
		this.ul.hide();
		this.img.unbind("click");
	}
});

Example 5: generation list from <select>

All previous examples generats autocomplete from AJAX but you also can do this from html code of current page. You can replace existing select-boxes with autocomplete by using source instead of url. You can pass in plugin either string with selectors like '#select.class' or jQuery object $('#select.class'). Pre-filling and digit-only filtrating is enable.


$("#autocomplete5").autocomplete({
	source:"#select",
		onKeyPress:function(){
		var o=this;
		setTimeout(function(){
			o.ac.val(o.ac.val().replace(/[^0-9]+/g,""))
		},50)
	},
	fillin:true
});

Example 6: generation list from array

If you have no need to use AJAX or have no select-box on your page, you can generate autocomplete from array. Sorry but nested arrays are not supported so you can not use [{a:'a'},{b:'b'}]


$("#autocomplete6").autocomplete({
	source:['a','b','c','d','e'],
	fillin:true
});

Example 7: generation list from object

The same as above. Sorry but nested objects are not supported so you can not use [{a:'a'},{b:'b'}] or {a:{b:c}}


$("#autocomplete7").autocomplete({
	source:{a:'a',b:'b',c:'c',d:'d',e:'e'},
	fillin:true
});

Example 8: list position

Example of list position at the top of input box


$("#autocomplete8").autocomplete({
	url:'search.php',
	top:true
});

Example 9: real values

Example of real values in non writeable fields


$("#autocomplete9").autocomplete({
	url:'search.php',
	values : true,
	writable : false,
	onSelect:function(){
		alert(this.pairs[this.ac.val()]);
	}
});

Example 10: alternative setup

By onSetup event you can change all properties exept 'width' or change behaviour of elements after autocomplete created. This example demonstrate smooth animation to options list.


$("#autocomplete10").autocomplete({
	onSetup:function(){
		var self = this;
		self.url = 'search.php';
		self.img.unbind("click")
			.bind("click", function() {
				clearTimeout(self.close);
				self.scroll();
				self.ul.slideToggle("slow")
				self.ac.focus();
			});
	}
});

Example 11: progress animation

Example of real usage with event hndling and animation


$("#autocomplete11").autocomplete({
	url:'/content/polygon/search.php?type=json',
	onSuggest:function(){
		this.ac.css({'background-image': 'url("/content/source/autocomplete/progress.gif")'});
	},
	onError:function(XMLHttpRequest, textStatus, errorThrown){
		this.ac.val(textStatus);
		this.ac.attr({disabled:"disabled"}).css({'background-color':'#d0d0d0','background-image':'none'});
		this.ul.hide();
		this.img.unbind("click");
	},
	onDisplay:function(list){
		this.ac.css({'background-image':'none'});
		if (!list)
		this.ul.append("<div style='line-height:100px;text-decoration:underline;text-align:center;'>[Empty list...]</div>");
	},
	minchar:2,
	type:'json'
});

Example 12: custom data format

Example of how to use custom data format


$("#autocomplete12").autocomplete({
    source : [{a:'a'},{b:'b'},{c:'c'},{d:'d'},{e:'e'}],
    fillin : true,
    dataHandler : function(mask){
        var self = this;
        return function(i, n) {
        for (var key in n){
            self.cache[mask].push(n[key]);
        }
        self.store[mask] += self.mark(n[key],mask);
        if(self.values && !self.pairs[n[key]])
            self.pairs[n[key]] = key;
        };
    }
});

Example 13: cascading selectbox

Example of how create selectbox wich depends on another input field


$("#autocomplete13").autocomplete({
    url:function(self){
        var state = $("#c13").attr("checked");
        if (self.ac.data("c13") != state){
            self.ac.data("c13", state);
            self.cache = {};
            self.store = {};
            self.pairs = {};
        }
        return 'search.php?c13='+state;
    }
});

Example 14: autocomplete form selectbox

Example of how to customize selectbox with plug-in


$("select#autocomplete14").autocomplete();

Notice

There is no simple way to re-render autocomplete created from select-box or array (object). You just need to re-create it.


Donation

If you like this plugin please vote for it on jquery site


Thanks to

  • Damir
  • Connected
  • Joey
  • Pasha
  • Morleydots
  • Gianfrasoft
  • Andrea
  • Ztalker
  • WooYek
  • Naden
  • Andrea Riciputi


Advanced options

Properties

  • url - [String|Function] ajax url
  • source - [String|jQuery|Array|Object] css selector or raw html, jQuery object, array [], object {}
  • minchar - [Integer] The minimum number of characters a user has to type before the autocompleter activates (default 1)
  • delay - [Integer] The delay in milliseconds the autocompleter waits after a keystroke to activate itself (default 50 miliseconds)
  • fillin - [Boolean] Pre-fill in (default false)
  • width - [Integer] width of autocomplete (default 200)
  • type - [String] type of server responce xml or json (default xml)
  • top - [Boolean] position of the list (default false to the bottom)
  • writable - [Boolean] allows to user write his own option (default true)
  • values - [Boolean] keep values for options (default false)
  • partial - [Boolean] makes request to server after each new letter (default false)

Events

  • onKeyPress - fires when user press a button
  • onSetup - fires once when autocomplit created
  • onSuggest - fires after onKeyPress but before ajax request send
  • onSuccess - fires when AJAX retuns result
  • onError - fires when AJAX retuns error
  • onDisplay - fires before list of items shows
  • onSelect - fires when user picks up from list

Dependences

  • jQuery - requires jQuery 1.2.6 or higher
  • bgiframe - use bgiframe if installed
  1. 5 Май 2008 в 21:34 | #1
    Hi, your plugin is ok, but it lacks of an crucial feature. if you enter 3(or the minimum set number) characters ajax fetches search results... lets say I enter "des" and I get this following list: - desert - description - destination - despite - destruction now... if I add another letter AJAX SHOULD NOT GET THE LIST AGAIN!!!!!! in this case JS should only filter the list you already fetched in the first place!!! It is stupid to fetch again with AJAX just to get the shorter list. This way the whole thing would work a lot faster with lot less server requests! Why make a server call if JS can handle the job on the fly? damir
  2. connected
    23 Май 2008 в 09:42 | #2
    Уважаемый MABP, Спасибо за самый человеческий автокомплит из всех мною найденных. Пришлось добавить следующий кусочек кода:
    
    })// IE scroll bug
    .css({
       width:this.width,
       top:(this.container.offset().top
       + this.container.height() + parseInt(this.container.css("border-top-width"))),
       left:(this.container.offset().left + parseInt(this.container.css("border-left-width")))
    })  // Safari window.onLoad bug
    
    Без него с Сафари дивы с вариантами ответов отрисовываются не под полем ввода, а поверх него.
  3. joey
    16 Август 2008 в 13:38 | #3
    This really is a great autocompleter, with all the features that i expected from a good one. The only thing i'd like to see that is not implemented and misses to make your autocompleter "perfect" is a variable position of the suggestions. Most of the time, it's good to show the below the input field, but sometimes there's no space below (viewport or even entire document) and they should be displayed above the input fie, like a O.S. do. This would ensure a correct implantation everywhere. I thought about doing this by myself, but seriously, if you can do it and redistribute yours, it would be much cooler. Not that i'm lazy but in my search for the ultimate autocompleter, i found a lot that are only variations from others, and that's already a big mess to find which are the more elaborated, and which are still in development or not. Anyway, even if you don't wanna update it, thanks : it's already great like it is.
  4. Maze
    22 Август 2008 в 18:44 | #4
    в IE6 img с кнопкой выпадающего списка съезжает вниз и влево (на вторую строку input'а). При этом в Mozille 2 и IE 7 всё ок. Что делать - не знаю. Подскажите, люди добрые.
  5. 23 Август 2008 в 01:23 | #5
    @Maze, попробуй поиграться со строкой
    
    ($.browser.mozilla?20:22)})
    
  6. 6 Февраль 2009 в 08:20 | #6
    Люди помогите ,никак не могу разобраться как в одном из автокомплитов динамически изменить свойство css для кнопки(стрелки). Вот код:
    
    jQuery().ready(function($){
    
        $("#autocomplete").hover(function() {
            $("?????????").css("height","100px");
        })
    
        $("#autocomplete").autocomplete({
            source:['a','b','c','d','e'],
            onKeyPress:function(){
                var o=this;
                setTimeout(function(){
                    o.ac.val(o.ac.val().replace(/[^0-9]+/g,""));
                },50)
            },
            fillin:true
        });
    
    });
    
    У автокомплита есть елемент img и если писать из евента
    
    onKeyPress:function(){this.img.hide(); }
    
    все работает , так вот и не могу догнать что это за объект “this” , и как к нему обращаться из вне ! Помогите А…
  7. 6 Февраль 2009 в 11:03 | #7
    Самый простой способ добраться до картинки это
    
    jQuery().ready(function($){
        $("#autocomplete ~ .ac_img").css({});
    });
    
  8. 6 Февраль 2009 в 19:34 | #8
    Спасибо , а вот есть такая проблема , как на этот img повесить hover или mouseover ? конструкция типа
    
    jQuery(this).find('~.ac_img').hover(function(){})
    
    или
    
    $("#autocomplete ~ .ac_img").hover(function(){})
    
    на работает ?
  9. 7 Февраль 2009 в 03:10 | #9
    Почему не работает? Я вот только что написал букмарклет - все работает!
    
    javascript:(function(){jQuery("#autocomplete1 ~ .ac_img").hover(function(){alert('in')},function(){alert('out')});})();
    
    Проверить можно сохранив как закладку, вызвав и наведя на стрелочку в первом примере. Если я все еще не ответил на твой вопрос, то объясни нормально что ты пытаешься сделать, возможно есть другой способ
  10. 7 Февраль 2009 в 09:10 | #10
    Аааааааа ! Сам дурак , описал евенты в коде выше чем само определение autocomplete , ясно что ничего работать не будет !
  11. 7 Февраль 2009 в 10:55 | #11
    Большое тебе спасибо за ответ ! Я недавно начал изучение jquery и пока не селен в нем ! А сделать я пытаюсь вот что: На странице есть несколько форм ввода (input) с автозаполнением изначально я хочу чтобы эти формы никак не выделялись и были бес стрелки (в css .ac_img visibility hidden) , а при наведении на одну из них мышкой у нее появлялась стрелка и бордер. Но тут есть пара нюансов , при наводе на место где должна быть стрелка (img) когда форма еще не выделена не происходит нечего ! Тоесть когда .ac_img visibility hidden на ней не срабатывает евент ! Также когда перевожу мышь из формы на стрелку срабатывает onmouseout ! Да и вообще она ведет себя как будто не относится к форме !
  12. 7 Февраль 2009 в 11:05 | #12
    Вот код:
    
    jQuery().ready(function($){
     $(".1").autocomplete({
    		source:['a','b','c','d','e'],
    		onKeyPress:function(){
    			var o=this;		
    			setTimeout(function(){
    		o.ac.val(o.ac.val().replace(/[^0-9]+/g,""));
    			},50)
    		},
    		fillin:true
    	});
    var focused=false;	
    $('.ac_img').css("visibility","hidden"); //убираю кнопку
     $('input')                             //на всех инпутах
        .mouseover(function() {
            $(this).find('~.ac_img') 
    	      .css("visibility","visible");   //показать кнопку
    	    $(this).parents('.ac_conteiner')
    		  .css("border-color","#FFCC00");  //показать border
    		 })
    	.mouseout(function() {
    	   if(focused!=this){   //если не в фокусе
            $(this).find('~.ac_img') 
    	      .css("visibility","hidden");}   //убрать кнопку
    	    $(this).parents('.ac_conteiner')
    		  .css("border-color","#abadb3");  //убрать border
    		 })	 		 
    	.focus(function() {
    	    focused=this;        //запомнить где фокус      
            $(this).find('~.ac_img') 
    	      .css("visibility","visible");  //показать кнопку  
    	    $(this)
    		  .css("background-color","red");  //покрасить все поле 
    		 })		 
    	.blur(function() {      //очищает всё
    	    focused=false;
    	    $(this).find('~.ac_img') 
    	      .css("visibility","hidden"); 	  	
            $(this).parents('.ac_conteiner')
    		  .css("border-color","#abadb3");
    		$(this)
    		  .css("background-color","white");  
    		})
    });
    
  13. 7 Февраль 2009 в 11:57 | #13
    Не могу понять зачем ты описываешь одни и те же ивенты дважды, вполне хватит mouseover и mouseout
    
    javascript:(function(){
    jQuery("#autocomplete1 ~ .ac_img").hide();
    jQuery("#autocomplete1")
    .mouseover(function(){
    jQuery("#autocomplete1 ~ .ac_img").show();
    }).mouseout(function(){
    jQuery("#autocomplete1 ~ .ac_img").hide();
    });})();
    
  14. 7 Февраль 2009 в 12:22 | #14
    Ну так тут и проблема ! При таком коде:
    
    jQuery("#autocomplete1 ~.ac_img").hide();
    
     jQuery("#autocomplete1")
      .mouseover(function(){
       jQuery("#autocomplete1 ~.ac_img").show();
        })
      .mouseout(function(){
       jQuery("#autocomplete1 ~.ac_img").hide();
       })
    
    Если навести на стрелку она изчезает !!!!!!! Как будто она невходит в #autocomplete1 А пользователю то на нее нажимать надо !
  15. 7 Февраль 2009 в 12:25 | #15
    Кстати а как у тебя код в форуме выделять можно , или это только ты редактировать можеш ?
  16. 7 Февраль 2009 в 12:30 | #16
    а так все вобще просто
    
    jQuery("#autocomplete1").parent().mouseover...
    
    к сожалению только я(((
  17. 7 Февраль 2009 в 12:42 | #17
    Вот посмотри , пишу как ты говорил ! http://www.hamal.nozonenet.com/test2.php Но ее все равно глючит ! если мышку из вне навести сразу на стрелку все путем, а если изнутри , исчезает зараза !
  18. 7 Февраль 2009 в 12:51 | #18
    Там как-будто что-то еще есть между формой и стрелкой
  19. 7 Февраль 2009 в 13:03 | #19
    хм странно действительно подглючивает. не знаю что сделать :(
  20. 7 Февраль 2009 в 13:18 | #20
    Проблема только в Firefox , в IE и Opera все путем ! Я так понимаю ты тоже в лисе смотрел ! Буду пробовать играться с ($.browser.mozilla?20:22)}) Если есть идеи подскажи !
  21. 7 Февраль 2009 в 13:20 | #21
    Если честно идей нет, я сейчас пишу линкдамп и пакую чемоданы.
  22. 7 Февраль 2009 в 13:47 | #22
    Нарыл !!!! В стиле ac_input margin 1 пиксель стоял !
  23. morleydots
    12 Февраль 2009 в 12:42 | #23
    Уважаемый архитектор, подскажите как получить значение $key из $value
  24. morleydots
    12 Февраль 2009 в 12:44 | #24
    @morleydots Как получить значение $key из < option value=$key >...< / option >
  25. 14 Февраль 2009 в 10:57 | #25
    @morleydots пока что никак :( Можете повесить какую-то функцию на onSuccess, которая будет складывать значения. Я скоро собираюсь делать новую версию плагина, там надо будет убрать некоторые хаки связанные с определением браузера и могу добавить этот функционал, тем более что меня уже пару раз просили.
  26. 19 Февраль 2009 в 19:08 | #26
    Pasha и morleydots по вашим просьбам сделал новую версию.
  27. JR Benning
    20 Февраль 2009 в 20:14 | #27
    Hi, When I use the plugin in IE7 the results div (ac_results) appears to the right of the input. The distance increases as the page is resized wider. And decreases as the page is made narrower. Any thoughts on how I can fix this? Thanks. I love this plug-in and don't want to use any other.
  28. 20 Февраль 2009 в 23:18 | #28
    I have tested plugin via IETester but have not saw this bug. I think this is becouse you own css overrides plugins styles. Try to use !important to ac_results properties
  29. Gianfrasoft
    2 Март 2009 в 16:00 | #29
    I tryied your code but I don't know how to pass extra parameter to GET method in the url of autocompleter while I geterate them dynamically. For example, I tyied:
    
    	$("#automatic_item").autocomplete({
    		url: "address.php?ID=" + document.mainform.ID.value
    	});
    
    but if I modify the document.mainform.ID.value the url is not updated.
  30. 2 Март 2009 в 16:08 | #30
    this is known issue :(
  31. James Pittman
    2 Март 2009 в 18:10 | #31
    Hi - does this plugin have the ability to store typed items that are not in the list? None of your demos displayed this ability.
  32. 3 Март 2009 в 11:01 | #32
    If you want store new value you can type it (flag writable must be true), send to server, check if it exists in your dictionary and if it doesn't save it :)
  33. 5 Март 2009 в 09:24 | #33
    Спасибо за плагин, очень удобный и, видимо, лучший из всех мною видимых для jquery. У меня появился какой то странный баг. даже два
    первый
    <!---->
    из вашего примера, пришлось закоментировать строку, иначе появлялась вторая картинка.
    и второй, у меня вокруг инпута появляется двойной border, не пойму откуда он берется. у вас такого не было?
    спасибо
  34. 5 Март 2009 в 15:24 | #34
    Простите я так и не понял что вам пришлось закомментировать потому что парсер 'скушал' тэги.
    А по поводу бордера тут скорее всего дело в css от вашего сайта, они перекрывают стили плагина.
  35. 5 Март 2009 в 15:31 | #35
    @CTAPbIu_MABP div с ac_img надо убрать, по второму я пофиксил :)
  36. 5 Март 2009 в 23:52 | #36
    простите я наверное слишком сонный, зачем убирать ac_img?
  37. 6 Март 2009 в 01:01 | #37
    потому что если его не убрать появляется вторая картинка со стрелочкой чуть ниже инпута. я свои стили комментировал, ничего не помогало, пока не убрал этот div c ac_img
  38. 6 Март 2009 в 13:30 | #38
    Я вас не понимаю, поэтому сделал отдельный файл без каких либо стилей в котором подключил плагин, во всех известных мне браузерах он работает корректно. Покажите мне что нужно сделать чтобы там появился второй ac_img
  39. Andrea
    13 Март 2009 в 14:34 | #39
    After an input tag got the focus the user can't leave it just pressing the tab, no matter if something is selected or not. The user must use the mouse click to switch the the next field. Very inconvinient for the form usability. Could you fix this? Cheers, Andrea
  40. 13 Март 2009 в 14:50 | #40
    I will try :) this is somewhere on 124 line...
  41. 20 Март 2009 в 20:11 | #41
    @Andrea you need rplace line 124 with this one
    
    if ((/27$|38$|40$/.test(e.keyCode) && self.ul.is(':visible')) || (/^13$/.test(e.keyCode) && self.get())) {
    
    and comment out line 134
  42. 6 Апрель 2009 в 11:26 | #42
    @BritneySpearsNews@BlabberStar.com fuck your brain! if your sick database has only few completes - it is your problem. in my example i have over 100 completes and i want to send data to ajax every typos
  43. Foundtest
    21 Апрель 2009 в 20:33 | #43
    Возможно ли по нажатию на какую-либо клавишу (например Page Down) показывать весь список, независимо от того, что введено в форме?
  44. ztalker
    24 Апрель 2009 в 04:30 | #44
    plugin - рулит. Но есть один вопрос. Я не очень шарю в JQuery, и времени разбираться уже нет. Так вот: 1. Есть радиобатор (страны). 2. Есть автокомплит (города). 3. При смене радиобатона, нужно чтобы автокомплт сразу рефрешился на другой список (выбрав другую страну - менять список городов). Так вот с очисткой текущего значения, кэша маркера и дивака со списком - проблем нет, а каким событием можно загрузить новый список? Как добраться до методов автокомплита из радиокнопки?
  45. ztalker
    24 Апрель 2009 в 05:08 | #45
    по сути оно все работает. при вводе все подгружается, только по клику на картинку список пусто выпадает, пока что-нить не введешь. Вобщем может и не совсем правильно, но я назначил другое событие на клик кнопы и все заработало:
    
    onSetup:function(){
        var self = this;
        self.img.unbind("click")
            .bind("click", function() {
    		if (self.ul.css('display') == 'none') {
    		    self.suggest('show');
    		} else {
    		    self.ul.hide();
    		}
            });
    }
    
  46. 24 Апрель 2009 в 08:38 | #46
    пока что нет возможности делать каскадные списки
  47. ztalker
    24 Апрель 2009 в 09:15 | #47
    пока каскадные можно делать так! я сделал не меняя ничего в самом плагине.
    
    $("#region").autocomplete({
    	"source":{...},
    	"fillin":true,
    	onSelect:function(){
    		$("#__needClearCity").attr("value", 1);
    		$("#city").attr("value", "");
    	}
    });
    
    $("#city").autocomplete({
    	url:'/cities/',
    	"fillin":true,
    	onSuggest:function(){
    		if ($('#__needClearCity').attr('value') == 1) {
    			this.cache = {};
    			this.store = {};
    			this.pairs = {};
    			$('#__needClearCity').attr('value', 0);
    		}
    		this.url =  '/cities/region/' + $('#region').val() + '/';
            },
    	onSetup:function(){
    		var self = this;
    		self.img.unbind("click").bind("click", function() {
    			clearTimeout(self.close);
    			if (self.ul.css('display') == 'none') {
    				self.suggest('show');
    			} else {
    				self.ul.hide();
    			}
    			self.ac.focus();
    		});
    	},
    	"type":"json",
    	"writable":false
    });
    
    при этом правдо пришлось в форме добавить скрытый элемент __needClearCity чтобы понимать когда обнулять кэш.
  48. ztalker
    24 Апрель 2009 в 09:48 | #48
    упс. упустил строчку после "this.pairs = {};", чтобы кэш таки работал:
    
    $('#__needClearCity').attr('value', 0);
    
  49. 24 Апрель 2009 в 10:30 | #49
    я поправил прошлый камент, добавил строку из второго. Вместо поля __needClearCity можно использовать $("#city").data("needClearCity",true) я просто никак не могу продумать концепцию как это должно выглядить, у меня тут уже три доработки есть можно будет новую версию сделать
  50. ztalker
    30 Апрель 2009 в 10:07 | #50
    Нашел баг - в IE не корректно работает автокомплит при вводе русских символов в первом. Для исправления нужно исправить строку формирования ссылки на : this.url = '/cities/region/' + encodeURI($('#region').val()) + '/'; IE настолько слаб что сам ссылки не кодирует =)
Страницы комментариев
Комментирование отключено.