Unobtrusive jQuery autocomplete plugin with json key value support

2008-10-02

A simple autocomplete plugin that transparently works with a key value json array (hash).

jQuery autocomplete demo

You may ask why another jquery autocomplete plugin

Because there was no jquery autocomplete that had the following features all in one

As much as I hate reinventing the wheel, there was no good wheel in my case.

So here are some examples and explanations:

Examples

$("input#example").autocomplete("autocomplete.php");//using default parameters

$("input#example").autocomplete("autocomplete.php",{minChars:3,timeout:3000,validSelection:false,parameters:{'myparam':'myvalue'},before : function(input,text) {},after : function(input,text) {}});

Options

Download all necessary JQuery autocomplete files

Share this with the world

Related

Comments

Luke

Thanks a lot!! This is great and was really missing!!!

Posted on 2008-11-25 16:40:53
Neal

One apparent bug... if the drop down list fills and you click off the field (focus on field blurs) the drop down list remains (needs to go away).

Posted on 2008-12-06 14:36:55
Joe

Another possible bug, I may have found. When someone types in something not that is not in the json result, and presses [Tab] the input field is cleared.

Posted on 2008-12-30 20:28:57
rdi

To remove [Tab] bug, edit the line in "jquery.autocomplete.js":

From:
else if(e.which == 40 || e.which == 9 || e.which == 38)//move up, down

To:
else if(e.which == 40 || e.which == 38)//move up, down

Posted on 2009-02-14 21:16:08
Melle

Excellent code! Found a small bug in lines 61 and 85.

if (settings.before == "function")
...

should become

if (typeof settings.before == "function")
...

same for checking of the 'after' function.

Posted on 2009-02-26 14:15:39
John Morris

Any way to make the list appear quicker? it's taking like 3 seconds, an dI would like it to redraw after each keystroke.

Posted on 2009-03-20 12:37:15
enrico villa

Great job .. minimal and very effective !

tnx !

Posted on 2009-04-11 15:39:51
lhenry

I found it was very diffcicutl to use without the mouse.. tabbing would pass to the next field and leave the suggestion open

i added this line

if (e.which == 9) clear();

at the end of this code

//set selected item and input values

textInput.val( list.children().removeClass('selected').eq(selected).addClass('selected').text() );

valueInput.val( list.children().eq(selected).attr('value') );


now it works just as we are used to, just like the browser autocomplete (wich I defeated with
textInput.attr('autocomplete','off');

Posted on 2009-04-11 16:38:23
Guido

I needed a onselect function also. Your code was so clean, it was easy to add.
In the section of click(function ()
you can add :
if (typeof settings.onselect == "function")
{ settings.onselect(valueInput.val(),textInput.val());
}

Posted on 2009-04-28 10:37:25
Bouke

I will try out your plugin. It does however not work well in chrome, the position is not directly under the input box, but instead at the end of the page. Perhaps I can try to fix this.

Posted on 2009-06-12 02:56:03
Amnell

What the heck... can't get this thing to work... this is what i get from firebug in firefox: "$("input#example").autocomplete is not a function"

Anyone know what could be wrong?

Posted on 2009-06-22 18:36:56
Z

Melle posted a bug on 2009-02-14 14:16:08

Posted on 2009-06-23 17:50:44
Z

Hello,

This solution dosn't work, if you want to send to save the datas with ajax.
I think, this is better:
textInput.after('<input type=hidden id="' + textInput.attr("name") + '" name="' + textInput.attr("name") + '"/>').attr("id", textInput.attr("name") + "_text").attr("name", textInput.attr("name") + "_text");

Posted on 2009-06-29 16:07:33
matt

Thanks for the great plugin, and thanks Guido, i needed something on the click event as well. also, if the exact position of the textbox that the autocomplete is on changes before the autocomplete is used, the list will sill show up where it should have been before the change. My solution was to add:

list = valueInput.next().css({top: textInput.offset().top + textInput.outerHeight(), left: textInput.offset().left, width: textInput.width()});

between the
list.html(items);
and the
list.show().children().

don't know if thats the best solution, but it seems to be working for me.

Posted on 2009-07-15 22:34:08
Pepe

If the drop down list fills and you click off the field (focus on field blurs) the drop down list remains (needs to go away).

Posted on 2009-07-22 15:24:34
matt

Pepe, you are correct, here is another fix for this plugin to make it disappear when focus is lost on the inputbox

simply add the line:

textInput.blur(function(e) {if(jQuery('.autocomplete:has(.selected)').length == 0){clear();} })

after the click (~line 94) seems to fix it

Posted on 2009-07-27 23:02:43
matt

Another note, I just realize there is a big problem with Guido's on select code, in that if its not click by the mouse (and instead the person uses the keyboard) it will not be fired. The solution is to just add:

if (typeof settings.onClick == "function"){settings.onClick(valueInput.val(),textInput.val());}

in the

else if(e.which == 13)//enter
} else

section, putting it right about the clear worked well for me.

Posted on 2009-07-27 23:45:39
dana

no matter how hard i try, the z-index of the autocomplete UL does not go above the Google Maps CSS layer. What could be wrong? How do I change the UL.autocomplete z-index? I have changes this in the CSS and it does not do anything.

Posted on 2009-08-21 19:34:26
Nic

Amnell I had the same issue

this is what i get from firebug in firefox: "$("input#example").autocomplete is not a function"

I was loading twice jquery.js and one after initating the autocomplete.

Just remove the extra ref to jquery

Posted on 2009-08-24 04:59:36
ramesh

Hi

Excellent work. What i am trying is, I want to call a PHP function in the url

When i do so, i get the json output... but it is returned with whole html page structure. (I am using joomla)

Any help would be greatful

Posted on 2009-11-04 02:34:39
Heshan Peiris

nice one. thanks for sharing. helped me to grab the concept. :)

Posted on 2009-12-06 03:27:12
Antti

Man, this is nice but i dont get this work... sort of.
I got that demo working perfectly even when i changed query. BUT
when i changed 'example' name to 'phone' (field names,ids etc.) Nothing happens...?
ajax-php returns right stuf it is something else and i just cant get it.

Posted on 2010-01-22 16:01:14
Ricardo Löpez Rey ASTURIAS

Hello!!!

Great work!! Thanks a lot... but it isn't really JSON enable, JSON serialized data should be like [{prop1:"value1",prop2:"value2"}]
now it expect [{"value1","value2"}]...

Also in the getData() function you put inside the loop the assignation handlers for the events (hover, click...) so for every item back from the server, you do the same...

Anyway...!!! THANKS AGAIN!!!

My function....


function getData(text) {
window.clearInterval(typingTimeout);
if (text != oldText && (settings.minChars != null && text.length >= settings.minChars)) {
clear();
if (settings.before == "function") {
settings.before(textInput, text);
}
textInput.addClass('autocomplete-loading');
settings.parameters.text = text;
$.getJSON(url, settings.parameters, function(data) {
var items = '';
if (data) {
$.each(data, function(index, item) {
items += '<li value="' + item.id + '">' + item.text.replace(new RegExp("(" + text + ")", "i"), "<strong>$1</strong>") + '</li>';
});
list.html(items);
//on mouse hover over elements set selected class and on click set the selected value and close list
list.show().children().
hover(function() { $(this).addClass("selected").siblings().removeClass("selected"); }, function() { $(this).removeClass("selected") }).
click(function() { valueInput.val($(this).attr('value')); textInput.val($(this).text()); clear(); });

if (settings.after == "function") {
settings.after(textInput, text);
}

}
textInput.removeClass('autocomplete-loading');
});
oldText = text;
}
}

Posted on 2010-02-14 09:03:46
robb

Hi,

As I can see your plugin is communicating with server side (php script) by GET method. Any possibility to use POST method?

It seems script is not passing value from input box if mode_rewrite is enabled.

Anybody managed to use this autocomplete with some framework (cake, codeigniter)

Thanx in advanced!

Posted on 2010-02-18 17:13:15
robb

Hi,

As I can see your plugin is communicating with server side (php script) by GET method. Any possibility to use POST method?

It seems script is not passing value from input box if mode_rewrite is enabled.

Anybody managed to use this autocomplete with some framework (cake, codeigniter)

Thanx in advanced!

Posted on 2010-02-18 16:17:41
Marcelo

I need a clear example of how to put aditional data in other inputs, this pluggin is great, but I need to select a name and fill other seven inputs with other data (phone, address, etc) given a unique number, not a name ... I'm clear with JSON, but I can't understand the code of this ...

That will be greatly apreciated.

Posted on 2010-05-23 02:05:58
Mmou

When the key is a negative number (-2165162), the value in the hidden input is 0. It is ok on the li value though. Anyone knows what could be going on?
Thanks.

Posted on 2010-05-29 15:47:21
fil

i must say this thing just doesn't work properly

in IE8 it often gives a error 'null' is empty or not an object at line 77 in the js-file

Posted on 2010-06-19 23:17:13
takien

This doesn't really work.
The dropdown list will show everything everytime i type a keyword, not filtered.
what's wrong with this?
thankyou

Posted on 2010-08-10 22:57:46
buzzknow

its really work mate :)

its simple, only provide data on json, and everything will fine :D

thanks a lot

Posted on 2010-08-11 19:39:50
takien

Yeah.. Thanks, it works perfectly.:)
I have modified it become a fancy Facebook Friend Selector.
follow this link to see it in action, http://cektkp.com/test/friend/

Posted on 2010-08-16 17:47:52
Thomas

When I press move down (40) the first time, the second item in the list is selected. Does anyone know how to fix it?

Many thanks in advance!

Posted on 2011-05-30 12:08:32
Thomas

When I press move down (40) the first time, the second item in the list is selected. Does anyone know how to fix it?

Many thanks in advance!

Posted on 2011-05-30 12:08:23
Will

The onblur code suggested above has issues with chrome and older versions of IE if your results list requires scrolling. They both fire the blur event if the user scrolls in the autocomplete list, hiding the results!

I wound up removing the onblur stuff ( textInput.blur(function(e)...) and instead added live('click') listener to the body. If the event didn't come from within the autocomplete results, I fire the clear() function. Seems to be working well. I put it directly after the clear() function in the code.

--------------

$("body").live('click', function (e){
var $t = $(e.target);
// is the list even showing?
if($('.autocomplete>li').length > 1){
// did it come from within the autocomplete results area?
if($t.parents('.form-set-location').length > 1){
return;
}else{
clear();
}
}
});

--------------



Posted on 2011-08-16 00:11:04
Will

@thomas I noticed the same.

>>> selected = selected >= size - 1 ? 0 : selected + 1; break;

is the problem. To (inelegantly) work around it, I set:

>>> var changed=false;
up top with the selected and size declarations then changed the above line to

>>> selected = selected >= size - 1 || !changed ? 0 : selected + 1;
>>> changed = true;
>>> break;

I also set it to false in the clear() function.

Thanks to the 'Humble Programmer' for the original code. Very handy!

Posted on 2011-07-14 00:45:50
Khaled

How can I preserve the value and the text of the textfield after submission of the textfield after submission ?

Posted on 2011-10-31 19:31:29
Catalyst

@Will, thanks for posting the workaround to the down button selecting the second item.

Since you mentioned it was inelegant, here's the fix instead of the workaround of adding a changed var.

change selected = 0; to selected = -1; in two places (where it's declared up top and in the clear function.

Posted on 2011-12-05 18:45:27
Greg

you explain things well, but it did not work for me.
had trouble capturing 'this'. the workaround in comments were tried.
ended up using this - too bad she doesn't explain things as well as you do though ;-)
http://www.jensbits.com/2010/05/29/using-jquery-autocomplete-to-populate-another-autocomplete-asp-net-coldfusion-and-php-examples/

Posted on 2012-08-01 20:48:59

Make yourself heard

Categories

Subscribe

All Posts

All Comments

© Copyright CodeAssembly

All code is licensed under LGPL, unless otherwise noted

littlebubu