Copyright © 2012 Tom Coote. All Rights Reserved. Powered by WordPress themed by bavotasan.com.
** NEWS: I have release a version 2 of this plugin.
Here is my new suggest box as a jQuery plugin which now uses a JSON string to represent it’s search data. It will accept the data as a JSON string, the object that the JSON represents or a function that returns one of those two things. Here is an example;
$('input#suggestBox').jsonSuggest(jsonString);
The search data sent to the plugin is an array of objects. Each object must contain atleast a textvariable. Further to that in order to display an image in the results it can contain an image variable which is the path to an image and for extra text to be placed in the results but not used to search you can specify an extra variable. Of course as well as these variables which are used to create the results you can specify as many other variables as you want which will then get passed to the callback function if specified. For example I use an ID variable as thats what most applications will require.
As well as the required search data there are a number of options that the plugin accepts in order to change it’s behaviour;
- minCharacters : [default 1] Number of characters that the input should accept before running a search.
- maxResults: [default undefined] If set then no more results than this number will be found.
- wildCard : [default ""] A character to be used as a match all wildcard when searching. Leaving empty will mean results are matched inside strings but if a wildCard is present then results are matched from the beginning of strings.
- caseSensitive : [defautl false] True if the search is to be case sensitive.
- notCharacter : [default !] The character to use at the start of any search text to specify that the results should NOT contain the following text.
- maxHeight : [default 350] This is the maximum height that the results box can reach before scroll bars are shown instead of getting taller.
- highlightMatches: [default true] This will add strong tags around the text that matches the search text in each result.
- onSelect : [default undefined] function that gets called once a result has been selected, gets passed in the object version of the result as specified in the json string.
- ajaxResults : [default false] If this is set to true then you must specify a function as the searchData constructor parameter. This is because when this settings is true then results are retrieved from this external function each time they are needed instead of being retrieved from the data given on contruction. The searchData function must return a JSON string of resulting objects or the object which represents the JSON string. The function is passed the following paramenters;
- The search text typed into the input box
- The current wildCard setting
- The current caseSensitive setting
- The current notCharacter setting
- width : [default undefined] If set this will become the width of the results box else the box will be the same width as the input.
As you may have noticed in the options you can handle the search yourself by using an external function. If this is set than you have complete control over what results should show each time a user types in the input box. You can use this to retrieve results dynamically from where ever you want which is good for large database search’s etc. Finally the results box can be styled in anyway through the accompanying style sheet.
So if you want to see some other examples then visit my demo page. Apart from that please download the source and use it as you wish. Let me know in the comments if you have found this useful.
** NEWS: I have release a version 2 of this plugin.
Download the source
Visit plugin page at jQuery
Demo Page
Tested to work in the following browsers;
- IE8, IE 7 & 6
- FireFox 3.5
- Opera 9.64
- Chrome
- Safari for windows


June 2, 2010 at 11:38 pm
Awesome thank you! Looks very promising.
June 3, 2010 at 4:11 pm
Just a quick question. I have my data stored in a .json file and am loading it in via getJSON(). The data is stored as:
{“posts”:
[
{
"title":"My Title",
"url":"http://www.myurl.org/",
"topic":["listitem1","listitem2"],
“type”:["item1"],
“region”:”National”,
“scale”:”scale1″,
“description”:”paragraph description here”
}
]
}
This doesn’t work however when I send my data object to the suggest function. Any ideas?
June 3, 2010 at 4:29 pm
Hi, you need to do two things to get this working. Firstly each object in your array needs an id property. Secondly when you pass this JSON to the suggest box you must pass data.posts as that’s the array of data.
Hope that helps.
June 17, 2010 at 2:49 pm
Hi Tom,
Nice plugin. This is almost exactly where I’m looking for.
The problem I’m having is with an Ajax call for the json data. Because it’s async the script will continue and try to parse an object which at that time is empty. Do you have a fix for this problem?
Regards
June 17, 2010 at 4:00 pm
If you have a look at the demo page you will see that example 3 and example 4 can be used to get data via AJAX. Hope that helps.
June 18, 2010 at 10:15 am
Hi tom,
That won’t work. Today I came up with a fix for the problem “A user types and the browser freezes after every tick”, add a delay to the request and it’s not annoying anymore.
I will sent you the newer version of the script today.
Regards
July 5, 2010 at 1:59 pm
Great Share !! Thumbs up
July 6, 2010 at 12:52 pm
Hi Ruud, Today I added suggest box in a website,
But I can’t see any simple way to increase the width of the div expanding on input.
I tried fixing it in the provided .css file, still no luck.
Any comments, how to increase the width of the expanding box when I have a search box of only 18 columns (80px).
Regards
Roomee
July 6, 2010 at 1:22 pm
Hi Roomee, the plugin has a width option. Just pass in your desired width when loading the plugin.
$(‘#suggestBox’).jsonSuggest({width:400});
July 6, 2010 at 1:40 pm
Thanks Tom,
But I can see this working myside,
i am using class not ID for the searchbox.
jQuery(function() {
$(‘input.tsearchbox’).jsonSuggest(testData.products, {onSelect:callback});
$(‘input.tsearchbox’).jsonSuggest({width:400});
});
July 6, 2010 at 1:41 pm
Thanks Tom,
But I can not see this working myside,
i am using class not ID for the searchbox.
jQuery(function() {
$(‘input.tsearchbox’).jsonSuggest(testData.products, {onSelect:callback});
$(‘input.tsearchbox’).jsonSuggest({width:400});
});
July 6, 2010 at 1:49 pm
You need to do:
jQuery(function() {
$(‘input.tsearchbox’).jsonSuggest(testData.products, {onSelect:callback, width:400});
});
July 6, 2010 at 2:26 pm
nops, still not working , I also tried to fix it in the jquery.JSONSuggest.js
But there isn’t anything for width.
everything else is great but width for the DIV,
I wonder if I m missing any default value in the JS file with the name maxwidth or minwidth.
(function($){$.fn.jsonSuggest=function(searchData,settings){var defaults={minCharacters:3,maxResults:5,wildCard:”",caseSensitive:false,notCharacter:”!”,maxHeight:400,highlightMatches:true,onSelect:undefined,ajaxResults:false};
maxHeight:400 >>> minwidth:???
July 13, 2010 at 4:10 am
Hi Tom
I was wondering if you knew why your json suggest doesn’t work in the latest version of jquery 1.4. It does work it just doesn’t lose focus when you click out of it. So it always remains open. Are there any plans to fix this?
Cheers
Drew
July 13, 2010 at 4:29 am
Hi Tom
I fixed it by targeting the nearest div and hiding teh results on mouseover
$(‘#hp-layout’).bind(‘mouseover’, function(){
$(‘.jsonSuggestResults’).hide();
});
I’m sure you can come up with something for your plugin though otherwise your awesome plugin will no longer work with new versions of jquery
Cheers
Drew
July 13, 2010 at 8:40 am
Hi Drew, I’ll probably get around to it one day. Since 1.4 has come out jQuery have released their own auto suggest box UI component which is pretty good. I started a new project recently with 1.4 but never used this plugin but when I do use it with 1.4 I’ll no doubt do a fix for it too.
July 13, 2010 at 2:00 pm
Hi, thx for great plugin, but i have a little problem.
I’m using ajax to retrieve data, and i dont know how to wait until ajax is ready. I’m using jsonp with no synchronous support
var result;
(‘input#input’).jsonSuggest(
function(text, wildCard, caseSensitive, notCharacter) {
var surl = ‘http://myurl;
$.ajax({
cache: false,
url: surl,
dataType: “jsonp”,
jsonp : “callback”,
success: function(data) {
result = data;
}
});
return result;
}, {ajaxResults:true});
Result is returned before ajax is completed
so it’s empty
I tried delay() and similar but nothing worked
Thank you for any help. I’m hopeless.
July 13, 2010 at 3:42 pm
All you have to do to make the plugin compatible with jQuery 1.4 is to change
$().mousemove(function (e) {
pageX = e.pageX;
pageY = e.pageY;
});
to $(document) or $(window) instead, since jQuery 1.4 made that a breaking change, so it’ll return an empty jQuery object instead of taking the document.
July 27, 2010 at 12:42 am
Hi, we have a hopefully easy question..
How can we “remove” a json object or update it’s content?
E.g, we have a json object with a list of elements and when the user changes some value, we want to reload the json object with new elements.
Any help would be helpful.
October 20, 2010 at 9:14 am
I ‘m invoking the JQuery-autocomplete in the keypress Event of an input Field.
When i type the first letter in the text field the JQuery-autocomplete is getting invoked but no list box that matches the letter is coming.But when i press the second Key that List box will come.
Could anyone please help why it is not coming in the keyPress event initially?
October 20, 2010 at 9:20 am
You should invoke the plugin way before the user get’s to interact with the input box. Invoking it on the user’s first keypress is to late for that initial keypress for anything to have happened.
October 20, 2010 at 10:56 am
Thanks..It is working.
October 21, 2010 at 11:48 am
Hi ,
Can I know whether it is legal to customise the jquery.jsonSuggest.js.
I’m using jsonSuggest for implementing Suggester Box in my application(for commercial purposes) .
I have modified the following lines of code in jquery.jsonSuggest.js.
1)function selectResultItem(item){
obj.val(item.id);
//instead of obj.val(item.text) .Because we want to display id while selecting.
}
2)function buildResults(resultObjects,sFilterTxt){
$(item).append(”+id+’(‘+text+’)'+”);
//instead of $(item).append(”+text+”);.Because we want to show both id & text in the list.
}
3)function runSuggest(e){
if(settings.ajaxResults===true){
}else{
if((filterPatt.test(searchData[i].text)===bMatch )|| (filterPatt.test(searchData[i].id)===bMatch )){
//instead of if((filterPatt.test(searchData[i].text)===bMatch )) .Because we have to search match in both id & text
}
}
October 21, 2010 at 12:47 pm
Hi Rinchu, there should have been a license in the download of the plugin? It should be called copy.txt. Anyhow it’s the GNU general public license so yes you can edit it and use it for commercial purposes.
October 22, 2010 at 7:27 am
Hi Tom.
You mentioned that jQuery 1.4 has released their own auto suggest box UI component and you use it.
Could tell me what is compent name and how can I get it.
Thx!
October 22, 2010 at 10:26 am
Yeah it’s on their UI site. Here is the link http://jqueryui.com/demos/autocomplete/
October 24, 2010 at 12:26 am
[...] Tags: html, JSON I have two autocomplete scripts, one of them makes use of (A) php/mysql/html/jquery and the other makes use of (B) html/jquery/json. [...]
October 27, 2010 at 1:09 pm
If an user enters value other than Suggester values, is there any way to validate the data in jsonSuggest?
For eg: validation like “Invalid data entered”.
November 8, 2010 at 1:29 pm
I’m using jsonSuggest for implementing Suggester .
But after selecteing values from suggester Focus is not coming to the field.
My code snippet is as follows:
jQuery(fieldId).jsonSuggest(jsonString, {
maxResults:50,
width: 400,
wildCard:”",
notCharacter:”!”
});
Could anyone please help why focus is not coming to the field after selecting fro suggester?
Do i need to add any code in jquery.jsonsuggest.js?
November 9, 2010 at 11:55 pm
Nice one ! Thank you so much !
Is there a way to make something like that : {onSelect:Go_to_url} ?
I guess the answer is yes, but how ?
I have something like that in the json file for each object :
{“url”:”http://www.myurl.org/”,”text”:”mytext”,”extra”:”extra_info”}
I tried different ideas but nothing works :/ Can you help ?
Thx for this jQuery Plugin !
November 10, 2010 at 9:13 am
Hi Eric, check out example number 3 on the demo page which I think is what you’re after.
November 10, 2010 at 9:40 am
Hi Tom, thanks for the quick answer !
It works, i’ve replaced (in your core .js file):
‘+text+’
by :
‘+text+’
Brilliant ! Thx again for the plugin !
May 26, 2011 at 10:17 pm
Hi Tom, this is very useful code. Can you please elaborate on above topic? Is it possible to set onselect to point to an URL (for each object selected). I wasn’t able to see it working on example number 3. Thanks in advance…
May 28, 2011 at 6:49 pm
You can’t give it a URL for the onSelect method. onSelect can only be a function and gets passed the item that was selected. In that function you can do what you want though, like send the data to a URL.
November 12, 2010 at 1:50 pm
While using jsonsuggest in our application if we specify width in jquery.jsonSuggest.js as
$(results).addClass(‘jsonSuggestResults’).css({‘top’:(obj.position().top+obj.height())+’px’,'left’:obj.position().left+’px’,'width’:obj.width()+’px’})
I have set the height as maxHeight:400.
my scroll bar in suggest box is flickering when we navigate via mouse through the list.
If i remove width then there is no flickering.
But i have to use width property to increase the width of suggest box since the text is large.
Could any one please help?
November 12, 2010 at 2:15 pm
When you use the plugin you can specify a custom width for the results box as a configuration setting.
$(‘#textboxid’).jsonSuggest(data, {width:’200px’});
November 15, 2010 at 7:22 am
Hi,
I have specified the width in configuration settings as width :’200px’..
But i’m not able to see the whole text .Then i have modified width in js as ‘width’:settings.width.
Previously width settings was ‘width’:obj.width()+’px’ .
Then it’s width is increasing.But still scroll bar flickering issues is there….
It is changing based on scroll Bar height…
Also one more issues i have faced is:
How to make keyboard navigation through suggestion list can be made better?
Because in my application user uses keyboard to navigate through list.
It is seen that scrolling through mouse is faster than Up & Down keys.
November 16, 2010 at 10:37 am
Dear Tom,
Thanks very much for this excellent component. Data display is very fast compared to other autocomplete solutions available.
One area of improvement i can see is the keyboard functionality. Support for page-up and page-down, smooth keyboard scrolling etc would be a value add. When the user scrolls down the data which are above the selection is not visible.
Any plans to address these issues in near future?
Regards
Krishna
November 16, 2010 at 10:48 am
Hi, thanks for your comments. I agree with your idea’s however I don’t have any plans to enhance this plugin any further since jQuery released their own autocomplete component as part of their UI suite. I just don’t have the same amount of time these days and I’m sure jQuery have a bunch of developers working on their component.
November 16, 2010 at 12:06 pm
Thanks very much for the reply Tom, really appreciate it.
I have tried the jQuery UI autocomplete. Unfortunately it takes lot of time to display the values if the data is more. So I could not use it because user experience is the prime factor.
regards
krishna
November 20, 2010 at 3:43 am
I ‘m invoking the JQuery-autocomplete in the keyup Event of an input Field.
I’m using ajax to retrieve data & I have set ajaxResults:true.
When i type the first letter in the text field the JQuery-autocomplete is getting invoked but no list box that matches the letter is coming.
There is data in the resultObjects.But function keyListener(e) is not invoking for the first key press.
But when i press the second Key that List box will come.
Could anyone please help why suggestion list is not coming initially?
November 23, 2010 at 6:45 am
Hi there, awesome plugin. I am having an issue where when i search it returns results, however when i use arrow down and hit enter it only passes the letters i keyed in to the search result page. You can see here http://nmit.studiomoso.com.au/ then use the search there.
November 24, 2010 at 9:21 am
If you point me towards the JavaScript file that has the code in I could take a look.
November 24, 2010 at 9:27 am
I think I know what the issue is here. The search box is in a form, so when you’re pressing enter the web browser is submitting the form at that point which is before the input box is given the search result value that was selected. My recommendation is to put the search box inside a div which has a keypress event on it. Check the event for the enter key and stop it from going any further up the DOM tree. This will allow the user to select a search item but will not submit the form. There are other criteria on that form that they may wish to fill in anyway before pressing the search button!
December 7, 2010 at 11:39 am
Dear Tom,
We are using your component. We have a requirement to support multiple selections. User should be able to select multiple items from the drop down. Any suggestion on how to go about?
regards
krishna
December 8, 2010 at 3:24 pm
managed to wire it all up.
Ive made some modifications to your code to make the experience nicer.
One of them is when you hit the escape key, the default neature of a txt input is to undo your change, so i figure clear and hide the short list, in your keylistener function add the following case
case 27: //escape key
$(results).html(”).hide();
return false;
Im also going to put this into a .net control so multiple instances can exist on a single form
if you want an updated copy of the version i have running let me know
January 5, 2011 at 5:02 am
Dear Tom,
We have modified your code to suit our requirements. Modification include the following:
1) Keyboard scrolling issue corrected to make it behave as any normal dropdown scrolling.
2) Page Down, Page Up key support for scrolling
3) Multiple selection using shift/ctrl keys using keyboard and mouse.
4) View more and View previous options to avoid scrolling performance issue if the records are more. Currently 400 records are displayed and then user can use the View More option to display more records.
Let us know if i should contribute the modified code back to you.
Regards
Krishna and Rinchu
January 5, 2011 at 1:55 pm
Hi Krishna,
Would you like to send me the code? I’d like to see it because I may release an updated version with your code included.
January 6, 2011 at 5:48 pm
Hello,
I have made an modification to your suggest/search box, that allows user to select the item with enter key like in normal gui applications without sending the form.
The code I added is (keydown listener):
obj.after(results).
keydown(function(e) {
if((e.keyCode==13)&&($(results).is(“:visible”))&&(!(typeof currentSelection === ‘undefined’)) ) {
e.stopPropagation();
e.preventDefault();
}
}).
keyup(keyListener).
Greetings,
Rysiek
February 22, 2011 at 7:52 pm
[...] have updated my previous auto suggest box plugin for jQuery. It has been a long time coming, the improvements are a [...]
May 23, 2011 at 1:47 pm
Hi there,
I am trying to use your jsonSuggest js file in my code, but unfortunately its not working. I am working on firefox 4.0 version. Please let me know ASAP if there are any changes to be made to the code, so that it works on FF4. Any help would be appreciated.
Thanks,
Ravindranath
May 23, 2011 at 2:01 pm
Hi, it’s been tested in FireFox 4 and works well. Do you have an example of it not working on the web so I can see?
September 1, 2011 at 5:24 pm
First thing first!
Thank you for your code. It is very hard to find such a nice script. It’s work on every Browsers! I was wondering about one thing: is there any size limitation? Because i have plan to use on chrome extension as dictionary -> auto-suggest and i will have 80000 words or more.
or
can we have something like:
var FA = str.substr(0,1);
$.getJSON(FA +”_wordlist.txt”,
function(data){
$(‘input#suggestBox3′).jsonSuggest(data, {maxResults:20});
}
);
thank you
khen
September 1, 2011 at 5:42 pm
I’m not sure how it would perform with that many possible results, slowly at a guess. If you use the max results setting then performance would be better depending on what was searched for.
October 31, 2011 at 8:39 am
I am using your JSON suggesBox script and still fairly new to javascript.
I am hoping from the result selected to be able to use the item ID as part of a URL
i.e. http://www.sitename.com/index.php?option=com_jumi&fileid=78&Itemid=177&SID={item.id}
but for the life of me cant work out how to do this, I assume that it is in the callback(item) code.
function callback(item) {
alert(‘You selected \” + item.text + ‘\’\n\n’);
}
Any suggestion would be appreciated or if there is a better way to do this.
October 31, 2011 at 9:08 am
If you’re passing an array of data to the plugin then the callback function will receive the array item that was selected by the user. So if your array is…
[{id: 1, text: 'one'}, {id: 2, text: 'two'}]
…and the user chooses ‘two’ then the callback will be passed the second item which would be {id: 2, text: ‘two’}. Find inside the function you can then use item.id or item.text for what ever you need.
October 31, 2011 at 9:09 am
just found out my answer
function callback(item) {
setURL = ‘http://www.afltcc.com.au/index.php?option=com_jumi&fileid=78&Itemid=177&SID=’ + item.id;
window.location.assign(setURL)
}