Home > jQuery Google Suggest > JQuery Google Suggest (jquery.gsuggest.js)

JQuery Google Suggest (jquery.gsuggest.js)

December 9th, 2009

I was unable to find an jQuery autocomplete / jQuery autosuggest plugin available that met my exacting standards. While there are a good number of plugins available in the plugin repository, they are either too large, poorly written, or simply do not work as expected. In addition to this, the ones I reviewed lacked extensibility and a good default configuration.

I decided to write my own jQuery autosuggest plugin (GSUGGSET), and give back to the community.

Project Requirements

  • memic the behavior of Google Suggest
  • make implementation as easy as adding suggest=”yes” to an input:text
  • allow for simple integration of ajax or inline datasets
  • intelligent caching
  • light weight

Default Configuration

  • ‘debug’: false
  • ‘url’: ‘/suggest.cfc’
  • ’size’: 10
  • ‘cacheenabled’: true
  • ‘cacheaggressive’: false //false – when user press ESC cache set is deallocated, true – cache set exist for duration of session
  • ‘cacheforward’:false, //true – complete cache dataset, false – incomplete cache datasets
  • ‘casesensitive’: false
  • ’sort’: true
  • ‘css0′: {’position’:’absolute’, ‘z-index’:’1′, ‘display’:’none’}
  • ‘css’: {’background-color’:’#ffffff’, ‘border’:’solid 1px #000000′, ‘margin’:’0px’, ‘cursor’:’pointer’, ‘color’:’#000000′, ‘padding’:’0px’}
  • ‘highlight’: ‘#bcd5ff’

Usage Information

While I wrote this plugin to be as simple and intuitive to use, there are some things you should be aware of before using it.

  1. The dataset used by the plugin must be a JSON String Array.
  2. There are two ways to assign a dataset to the input:text:, Inline & AJAX
  3. The nosubmit attribute you see in the examples above prevents the form from submitting when enter/return is pressed. This overrides the default browser behavior, but it is up to you to decide if you want to use this.

————————————

A. Using an Inline Dataset

An inline dataset is one that does not make a round trip to any server to get a collection of data used for the suggest-box. To use this, simply add the parameter suggestvalue=”" to your input:text. Note, the suggest_value must be a JSON Array.

html: <input type="text" name="attorney_name" value="" size="100" suggest="yes" suggestvalue='["Micah","Shawn","Charles"]' nosubmit>

*The sugget_value does not need to be sorted, thats handled automatically.

B. Using an Ajax Dataset

An AJAX dataset is one that communicates with a server in the background to get a collection of data (when necessary thanks to caching) used for the suggest-box. To do so, you will need to pass the address of your ajax call (wether that be a cfm page, asp .net, php, whatever) to the URL Config Option.

jQuery(document).ready(function(){jQuery.gsuggest({'debug':true,'url':'myAjaxPage.aspx'})});

That page will receive two url parameters in its get request: value & method. value is the value of the input:text after keyup and should be used to execute a query and return a JSON String Array. method is an identifier to allow multiple queries to be executed inside a single ajax page. I prefer to have all of my suggest queries in one file, suggest.cfc, and you will see that reflected in the defaults.

html: <input type="text" name="attorney_name" value="" size="100" suggest="yes" nosubmit>

MIT License/GNU License

http://www.opensource.org/licenses/mit-license.php

http://www.gnu.org/licenses/gpl.html

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so.

No related posts.

jQuery Google Suggest

  1. | #1

    Hi
    Thank you for sharing this code.
    I have one question… Can this be used in cases with 2 (or more) fields, each with its own ajax dataset?
    Rds.

  2. | #2

    Yes, absolutely.

  3. | #3

    @Micah Lacombe

    Just to be more clear: you can either embed multiple queries inside a single file and use the method parameter to determine which needs to be executed (as I do), or you can specify a different config url for each input:text and have your ajax code in separate files… how you decide to use it is up to you.

  4. | #4

    I just clicked your “SEE IT IN ACTION” link, and all that came up was binary data.

  5. | #5

    Hi Keith,

    Thanks for bringing this to my attention… I had a catastrophic hard drive failure in December and some files were lost. I rebuilt the sample “SEE IT IN ACTION” page this morning so you can check it out. Let me know if you have any questions!

    I would like to also add that if anyone has trouble getting the script to work, or understanding it, just make a comment here and I will follow up with specific details.

  6. Yugi
    | #6

    Hi,

    Can you write your gsuggest to support json format?

  7. | #7

    Hello – Can you give more details on your suggest.cfc file? I’m not familiar with ColdFusion, but I would like to add this functionality to my site using PHP. What exactly should the server side (CF, PHP, .NET, etc.) look like?

    Thanks for this work, it seems like it will be perfect for my application.

  8. | #8

    @Yugi

    Hi Yugi,

    I am not entirely sure what you mean… in fact it requires the dataset to be in JSON already. Can you explain more about what you are looking to do?

  9. | #9

    @Brian

    Brian,

    Don’t be scared off by the CFC. It is essentially the same thing as an object in any other language. In this particular case however it is a remote object, aka a Web Service. You can create your own Web Service in cf, php, .net, etc. That having been said you could also implement it without object remoting by doing an evaluate on the appropriate url parameters… the only requirement here is that the data is returned to gsuggest in the correct format.

    Here is the code for the CFC:

    http://www.micah-lacombe.com/utils/suggest_cfc_code.cfm

    Notice the comment at the bottom:


    <!---
    var method = obj.form.name + '_' + obj.name;
    var surl = $.gsuggest.config.url + "?method="+method+"&value="+objval+"&callback=?";
    --->

    This is where gsuggest sets up the url to use during the ajax call. As mentioned in the main article, [method] is the name of the method which gets executed, and [value] is the value currently in the text box. CF uses [method] as part of its remote call, however other languages may be different…. so you can update gsugggest.js to reflect whatever type of url you need and even add multiple language options by enhancing the configuration. Also, [callback] is something jquery uses (so that is also required).

    The data you return needs to be formatted in JSON:


    "#callback#(#serializejson(listtoarray(valuelist(qcustomers.contactname)))#)">

    This is outputing the value of [callback] as a function, hence the parenthesis. And the parameter value of that function is simply a JSON Simple Array. For further CFML Details, hit up google or ask me.

    Good luck and let me know how it goes!

  10. | #10

    @Brian

    I was thinking about this some more and realized I forgot to mention that you don’t really need to use a web service if you don’t want to. You can actually specify a separate file for each input by using a different config on each. If you take a look at the script you’ll see how to do this but if you get stuck or need a sample let me know.

    I prefer to consolidate everything in one place (aka one file) because it keeps it easier to manage… but that all depends on how your software is engineered.

  11. Jacek
    | #11

    Hi,
    I’ve a big trouble with your script. I cannot force it to work on my localhost (W7, Apache, PHP). I’ve done the following:
    1. I’ve copied the example (“SEE IT IN ACTION”) to may local machine and named it index.html
    2. I’ve also copied jquery-1.3.2.min.js and jquery.gsuggest.js and run the script with the ‘url’=http://www.micah-lacombe.com/utils/suggest.cfc and it’s OK in Firefox but not in IE8 and IE6 (XPMode)!
    3. I’ve place a call to suggest.cfc in FF:
    http://www.micah-lacombe.com/utils/suggest.cfc?method=gsuggest_customer&value=a&callback=?
    and it has returned:
    ?(["Alejandra Camino","Alexander Feuer","Ana Trujillo","Anabela Domingues","André Fonseca","Ann Devon","Annette Roulet","Antonio Moreno","Aria Cruz","Art Braunschweiger"])
    4. I’ve prepared local file ‘suggest.php’ that contained the above string:

    5. It is not working! The string from suggest.php is always the same regardless of input:text value but even for ‘a’ it’s not working.

    Any suggestions?

    Regards,
    Jacek

  12. Jacek
    | #12

    My suggest.php file:
    echo ‘?(["Alejandra Camino","Alexander Feuer","Ana Trujillo","Anabela Domingues","André Fonseca","Ann Devon","Annette Roulet","Antonio Moreno","Aria Cruz","Art Braunschweiger"])’;

  13. | #13

    @Jacek

    Jacek,

    Your file will always contain the same content because you defined a static JSON set i.e. ‘?([“Alejandra Camino…

    Using my file as a remote call to test won’t work either. You need to have your class that returns the JSON on the same domain b/c gsuggest uses $.getJSON and not JSONP.

  14. Jacek
    | #14

    Hello,

    Your are right: I’ve defined static script in PHP that always returns the same content for testing purposes only – IMHO as long as I enter a single ‘a’ letter in input field it should work but it doesn’t. So that’s why I asked you about the output format of your suggest.cfc script. Properly formated JSON array is like: ['A...','A...','...'] but it’s not working in this case, too.
    So pls, tell me what the output format of AJAX data should be like?

    BTW calling your script from other domain works in FF 3.6 but not in IE8 – I understand it it’s security issue.

    Jacek

  15. | #15

    Your JSON Array is structured just fine, but you need to have the “?” replaced with the value in the URL parameter named “callback” aka. $_GET["callback"].

    As I said before, if you need cross domain support for your callback you can modify the code to use JSONP.

    Happy coding 8-)

  16. | #16

    I get the following error:

    JQuery is not defined
    [Break on this error] })(JQuery);
    jquery…gest.js (line 195)
    jquery is not defined
    [Break on this error] jQuery(document).ready(function(){jque…({‘url’:'scripts/getJudges.php’})});

    The code is as downloaded. I am trying to call a php function.

    query($sql);

    $js[]=”";
    while($row=mysql_fetch_row($result)){

    array_push($js,$row);
    }
    array_shift($js);
    $jcode=json_encode($js);

    echo $jcode;

    ?>

  17. | #17

    Any chance of you putting this code on Github? It’d be great to have a place to check for possible future bug fixes. Thank you!

  18. b_dubb
    | #18

    $(“input[suggest=yes]“).each(function(i){
    if (this.id == null || this.id == ”)
    $(this).attr(“id”, “_g��gg꧆_”+i)

    just downloaded the file and it looks like some characters have turned into gremlins. getting an error on page load …

    jQuery is not defined
    [Break on this error] })(jQuery);
    jquery…gest.js (line 195 )

  19. Jeff
    | #19

    How can i get this to fire the enter key when a suggestion is selected via mouse click? . . The enter key fires a keypress event which fires a defaultbutton.click event.

  20. Jeff
    | #20

    I’d like to get this to fire an enter key keypress event when a suggestion is selected via mouse click.

    Firing the enter key will trigger the DefaultButton click for that focus area. Any help?

  21. Arya
    | #21

    Hi Micah Lacombe,

    On my local setup auto suggestion is working perfectly when I type a new letter,but when i type the same letter it does not show any suggestion.

    url is : http://localhost:8080/velocity/auto which returns : jsonp1282306912797(["Carine Schmitt","Carlos Gonzalez","Carlos Hernndez","Catherine Dewey","Christina Berglund"])

    ajax request is : http://localhost:8080/velocity/auto?method=gsuggest_customer&value=v&callback=jsonp1282306912797

    when I compared my code with yours example I noticed &_=somedigits is missing from url.

    Can you please tell me what going wrong here ?

    Thanks
    Arya

  22. Stefan
    | #22

    Hello,

    your script is working great, but only when I place the array inline into the input field. Like “Jacek” it is very hard for me to make it work using Ajax call to php script. Finally I have made it work when I placed in the php file the following code:

    Now it is showing me the list when I enter the “a” letter, but when I continue to type it “suggests” me everything, regardless of what I am typing. For example when I type “america” I am still able to see the string “Anabela Domingues”. In this case only the first seven letters from the “Anabela Domingues” string are not bold.

    I am working for a few hours on this, and I eventualy will get it work soon, but please write some more information for the other php developers. I am sure that it will be very useful for them and I am confident that it really shouldn’t be so hard to make things work.

    Thanks in advance!

  23. Stefan
    | #23

    Hi,
    the code from the above post is :

    print $_GET["callback"].’(["Alejandra Camino","Alexander Feuer","Ana Trujillo","Anabela Domingues","André Fonseca","Ann Devon","Annette Roulet","Antonio Moreno","Aria Cruz","Art Braunschweiger"])’;

    I am writing it again, because it didn’t show up in my previous comment.

    Best regards!

  24. Stefan
    | #24

    Hi again, I figure out everything. The problem from my first comment occured because I hardcoded the JASON array, so it will always appear the same. Now the script is working just fine. Thanks :)

  25. | #25

    @Trevor Turk

    Trevor, feel free to post and share this script freely. Just be sure to include the licensing information and credit back to me.

  26. | #26

    @Stefan

    Stefan,

    Glad you got it working! I moved and started writing software for the airspace industry so I have been away from the blog all together until now.

    Peace

  27. | #27

    @Jeff

    This behavior is supported. You will need to modify the click event to have it submit once the input field has been updated.

    # $(suggest_idChildren).live(“click”, function(){$(this).parent().prev().attr(“suggestLast”, $(this).text()); $(this).blur(); $(this).parent().prev().focus(); return false;});

    *see above line, this is where you would add in your submit (rather than firing a key event… but you could do that if you wanted to). Off the top of my head it would look something like this: $(this).parent().prev().Form.Submit() but don’t quote me on that… use FireBug and or an DOM viewer to trace back to the object you want to submit on.

  28. | #28

    @Arya

    Without being able to see your code I can’t really offer much help. Can you post it on a publicly available URL?

  29. | #29

    @b_dubb

    Thats because of the unicode characters in there… you can take those out. I should probably remove them from the code base and update the release on the jquery site.

    Just replace them with something you feel would be adequately unique and it’ll work fine.

  30. | #30

    @Jacek

    You need to include your callback reference or the JSON won’t be processed. Let me know if you are still having trouble and provide me with a link to your source. I’ll help out when I have free time.

    peace

  31. | #31

    @Dale

    Looks like you aren’t including the jquery library… check all your references.

  32. | #32

    @b_dubb

    I went ahead and removed those characters for you and changed it in the source linked from this website. Unfortunately I cannot add a new release to the jquery plugin site b/c their system is down:

    Ref. http://forum.jquery.com/topic/plugin-repository-status

  33. | #33

    Dale :
    I get the following error:
    JQuery is not defined
    [Break on this error] })(JQuery);
    jquery…gest.js (line 195)
    jquery is not defined
    [Break on this error] jQuery(document).ready(function(){jque…({’url’:’scripts/getJudges.php’})});
    The code is as downloaded. I am trying to call a php function.
    query($sql);
    $js[]=””;
    while($row=mysql_fetch_row($result)){
    array_push($js,$row);
    }
    array_shift($js);
    $jcode=json_encode($js);
    echo $jcode;
    ?>

    when I echo / print in PHP

    this print
    [["AMISANI SOEROSO"],["HAMID MUNDZIR"],["Aminudin Bisri"],["Fauzi Amin"]]
    and nothing to show up
    can you help me?

  34. | #34

    Great plugin. Had no problems installing or configuring this and it performs just as good as Googles autosuggest so thanks :)

  35. | #35

    @Kredittkort

    Cool, glad you like it!

  36. | #36

    @adhie

    make sure you are including jquery before the addon

  37. nick
    | #37

    @Stefan
    wow, finally i get this working with your little snippet, thank you! the author should include a .zip file with all the files needed, because it looks like a lot of people are having a problem with what to put in the .php file or .cfc or whatever. I’m pretty new to all of this, and a .zip would have had me up and running instantly, but again it’s a situation where a developer thinks everyone knows exactly what he knows and doesn’t think about all the people who are a bit newer.

  38. nick
    | #38

    holy crap, it’s not even working, it’s displaying ALL of the reults even though i’m just typing LLLLLLLLLLL, and it’s saying that it’s matching ANABEL… RRRRRRRR WOW

  39. nick
    | #39

    Stefan :
    Hi again, I figure out everything. The problem from my first comment occured because I hardcoded the JASON array, so it will always appear the same. Now the script is working just fine. Thanks

    how did you get it working? i used the code you posted and it actually showed the suggest box this time, but if i keep typing the letter A, it will say it’s matching ALEX when i’m just typing AAAAAAA

  40. nick
    | #40

    trying to get ajax to work, if i type any character, all of the results are shown, but then if i delete that character and type it again, it will show the correct results. So if I press A, it will show all of the results, even “Benji” “Bon”, etc. but then if I push the backspace key on my keyboard, then type A again, it will correctly show only those results starting with the letter A, and it will work correctly, until I delete A, and with an empty input box i press B, then it will show all of the results again, but when i press the backspace key, then type B again, it will correctly only show those results starting with the letter B.

    Do you know why this is happening?

  41. | #41

    @nick

    Nick, the query you are using to generate your ajax return for the gsuggest code is not correct. You must filter the data that is passed to the cached set or it will not match correctly.

  42. owls
    | #42

    For inline, it needs to be suggest_value, not suggestvalue.

  43. Krishna
    | #43

    Hello,

    Is is possible to support searching in between string rather than searching only for the first character?

    Say for example if i press ‘a’, it should display both apple and orange because both contains the character ‘a’.

    Regards
    krishna

  44. RR
    | #44

    while trying to use jquery.gsuggest.js in our application i’m getting an error
    as “Object Doesn’t support this property or method” in the method
    jQuery(document).ready(function(){
    $(this).mousemove(function(e){ ———————>Line throwing Error

    if ($.gsuggest.mousepos != e.pageX+’-'+e.pageY){
    $.gsuggest.synctext = true;
    $.gsuggest.mouseoverok = true;
    }
    $.gsuggest.mousepos = e.pageX+’-'+e.pageY;
    });
    })

    Could any one please help?

  45. | #45

    @Krishna

    …As I recall you should be able to do that quite easily by modifying what JSON is returned from the query. As for doing it inline, you would have to change some of the programming but it would not be very hard.

  46. | #46

    @RR

    I can’t really help you without having a link to the page… try using FireBug for JS Debugging it works great.

  47. Marc
    | #47

    Hi Micah,

    I’ve been trying to get this to work for two days now. I can get the inline version to work with no problem. I’m trying to get AJAX to work with php. For the life of me, I just can’t seem to get a properly formatted JSON array out of php, even just trying to echo plain text. Obviously I’m doing something wrong. I was wondering if you could post a working php analog to suggest.cfc? If you could find the time, it would really be helpful.

  48. Chris
    | #48

    It works great on a normal page, but when I try to use it on a page displayed within a JQuery UI Dialog box the drop-down appears offset from the input and although hovering the mouse over the selections changes the input to the correct value, when I select it, the input then returns to just what has been typed.

    It seems the amount the drop-down is offset is similar to the centering distance of the dialog. I’m guessing it’s something to do with the css0 and css but whatever I change them to doesn’t seem to work. Any clues?

  49. stan4th
    | #49

    Hi,
    first, this is great thanks.
    I’m adding this to an ASP.NET app which was written in classic ASP.NET – I wondered how I deal with an AJAX call from gsuggest, can I pass the method as well as the aspx page. Would you provide a quick example please?
    Thanks

  50. eric
    | #50

    Everything works fine, exept for 1 thing: the position! The box appears way off the page instead of hanging under the input field.

    Does anyone know why?

  51. HB
    | #51

    great plugin! One question: We are running the gSuggest now in iFrame. When clicking the inputbox with the mouse, the cursor always jumps to the first position. This only happens with IE. Any clue?
    (You can test with your own demo running in an iFrame)
    Thanks.

  52. | #52

    @stan4th

    All you need to do is pass a JSON Array object back and it will use that in its drop down. This is explained in the documentation w/i this post…. keep at it and look at the javascript, you will figure it out.

    I still use gSuggest today on new applications and it works like a dream. Nice to know others are able to utilize it as well.

    Like always, I strongly recommend using firebug and running a trace. GL! -micah

  1. | #1