Ajax Auto Suggest v.2

Posted on February 07, 2007

ajax autosuggest

Update 2007-07-19

Version 2.1.3 - demo & guide here.

Download AutoSuggest v.2.1.3

  • Bugfix

Update 2007-07-07

Version 2.1.2

  • Smaller file size (under 9k)
  • Uses encodeURIComponent instead of encodeURI
  • bsn namespace is set as default - uses new bsn.Autosuggest(... instead of new Autosuggest(.... This avoids conflicts with other libraries (e.g. prototype) out of the box.

Update 2007-03-24

I've made a few changes, and shaved off a third of the file size.

Most importantly, using a function as the script variable, it's possible to include values from other fields in your AJAX request. A number of people asked for this functionality.

Compatibility with prototype, and other libraries (version 2.1 and earlier)

Hi to everyone that's having compatibility problems with Prototype or other libraries. Don't write me an email or a comment - here's how to avoid conflict problems:

Before you load the Autosuggest .js, set the following variable in your html page:

useBSNns = true;

This shifts the whole code into the 'bsn' namespace. You then create a new autosuggest as follows:

var as = new bsn.AutoSuggest('idOfTextfield', options);

Undocumented functionality. Sorry.

Tim.

Original post

The new and improved version of my JavaScript/Ajax auto suggest script. More features, less bugs. Demo and documentation here.

Improvements include:

  • Optional JSON Support
  • Callback function support (set ID when user selects list item, or anything else...)
  • Can display more information
  • An optional message when no results are returned
  • Completes field when enter key is pressed
  • Slick new look (2.0 ready!) including fade effect!


Comments (359)

Derek Punsalan said

Nice job with this one. Definitely looks sharp and something to take note of the next time something similar is needed for a side project.

Posted by: Derek Punsalan at February 7, 2007 09:37 AM .

Carlo said

Very nice thank you!

I do have a question:

I have a form with multiple fields which i like to "auto suggest". I've rewritten the test.php so it will query my MySQL database which works nicely. Now when I let the script auto suggest the first field i would like to update the query for the second field of my form. My db consists of up to 2M lines and its growing rapidly. If I could update the SQL statement every time "auto suggest" fills in one of the fields this would narrow down the results.
Is there any way AJAX can grab the content of the first and/or second or... field without submitting the form, or typing or selecting the field(s)?


TIA,

Carlo

Posted by: Carlo at February 7, 2007 02:16 PM .

bsn said

Hi Carlo,

If I understand you correctly, you have to textfields, A and B.
User makes a selection in A.

When she then starts typing in B, you want to pass the value of A as well as the input in B to your server-side script, so you can use two WHERE clauses in your MySQL query.

I'm afraid it's not possible with the current script, because it can only pass hard-coded variables and the input from the current field. I would have to add a custom function that creates the query url... Interesting idea though.

In the meantime, how about saving the first query as a session variable?

Cheers,
Tim.

Posted by: bsn at February 7, 2007 02:34 PM .

Carlo said

Hi Tim,

Yes this was suggested to me already. For now i will use sessions to store them. But it should be possible right? (I'm no AJAX guru). Strange that other people didn't request this option before, I guess other users could use this too.

Anyways, thanks for the tip.

Br,

Carlo

Posted by: Carlo at February 7, 2007 03:23 PM .

Hamilton said

Tks...this script is great...I realy like this because my ASP classic has a perfect work in this script and very easy to use it.

My only problem is ãáíà, my database is in portugues-brazil and this is a problem to work in asp/sql...

but i work on that today and maybe i finish and pot here my solution...tks again and keep working like that...

Posted by: Hamilton at February 8, 2007 07:09 PM .

matteo said

i download files.
I crate my test.aspx
Change the code but i don't see nothing. White page. blank page.
v2 work in other environment???

Posted by: matteo at February 8, 2007 10:49 PM .

xitag said

could you give exemple from mysql database ?

Posted by: xitag at February 8, 2007 11:28 PM .

bsn said

Hi Matteo,

you'll have to change the structure of your xml document. Check the documentation on the example page.

Tim.

Posted by: bsn at February 9, 2007 12:10 AM .

bsn said

Hi Xitag,

I'm afraid that I'm not going to get into the details of retrieving results from a MySQL database here. There's a whole load of issues that have to be addressed, making it difficult to provide a concise example.

Tim.

Posted by: bsn at February 9, 2007 12:36 AM .

matteo said

Another problem.
Impossible to compress javascript.
There are some missing ";"
Can you provide a autosuggest_mini with code compressed?

Posted by: matteo at February 12, 2007 04:27 PM .

Manbeer said

Hi,

We are using .brandspanking "Ajaxauto Suggesion" we have two text box in one page may i know how can we do it

Please help Us

Manbeer

Posted by: Manbeer at February 13, 2007 04:23 PM .

bsn said

Hi Manbeer,

look at the demo page: there are two autosuggest textfields on it.
They need to have unique ids, and you need to create an autosuggest instance for each of them (look at the javascript at the bottom of the HTML source for the demo).

Tim.

Posted by: bsn at February 14, 2007 08:39 AM .

John said

It is sad that Tim doesn't want to supply a (simple) mysql example, does anyone else can supply me an example? I really need it.

John

johnbao at gmail.com

Posted by: John at February 15, 2007 02:33 AM .

MichaelK said

Ahhh, you have it passing the ID value as well now. I remember looking over the first version and I eventually had to make my own because it didn't do this. This would have saved me a bit of time if it was sooner :)
Or perhaps I should have posted my method online for people as well. Maybe if I had more time...
Well done though. For serious applications it should definitely work like this. I wish I could show my work but it's for my company, the autosuggests really do important stuff in what I made. Hehe, I'm an AJAX fool now. I have awesome dynamic stuff all over the place. Thanks for spreading the love :)

Well here's the bit of HTML that will create an autosuggest field in my method. It's pretty slick that you specify all the parameters in the HTML. Notice the parameters... it searches on "client_contact" table for two fields in this case! (it can be just one as well). "name_l" and "name_f".. and will autosuggest if you type 'Smith, John' for example, and the ID returned is called client_contact_id in the client_contact_table. 92 is the maxchars of the textfield (to prevent server load after field is full), 20 is the max number of results in the autosuggest dropdown (and the sql query), ac1_div is the div that's used for the autosuggest results, and the last parameter is the link that each result will have with the dynamic data being at the end as 'client_contact_id=%' and the % is replaced with the ID of that value.

[input type=text name="contact" size="30" maxlength="92" onKeyUp="autocompGen(document.form1.contact.value, 'client_contact', 'name_l%name_f', 'client_contact_id', 92, 20, 'ac1_div', 'view_contact.jsp?user=&case_id=&client_contact_id=%')"]

Posted by: MichaelK at February 15, 2007 03:55 PM .

bohu said

Hi to all,

very nice tool for any application.

I've added some functionality to highlight part of suggestion. you shold add the little part of code to the script to get a highlighting of the suggested result typed into the textbox. Please also add the following lines to in the function

_bsn.AutoSuggest.prototype.setSuggestions = function (req)
after the line:
this.createList(this.aSuggestions);
 
selStart = this.fld.value.length;
selEnd = this.aSuggestions[0]['value'].length;
this.fld.value = this.aSuggestions[0]['value'];
this.selectRange(selStart, selEnd);

And here the new function to add:

//
// Highlight part of text for typeahead
//
_bsn.AutoSuggest.prototype.selectRange = function(iStart, iLength)
{
  if (this.fld.createTextRange) {
    var oRange = this.fld.createTextRange();
    oRange.moveStart("character", iStart);
    oRange.moveEnd("character", iLength - this.fld.value.length);
    oRange.select();
  } else if (this.fld.setSelectionRange)
    this.fld.setSelectionRange(iStart, iLength);

this.fld.focus();
}

It works in FF, IE 6, Opera, Netscape 7.

Godd luck to all,
bohu

Posted by: bohu at February 20, 2007 12:03 AM .

sugarcrm_developer said

What is the current license for distribution? Is there a fee if we were to use code elements in a commercial product? Great Code! Thanks! - E

Posted by: sugarcrm_developer at February 20, 2007 04:05 PM .

cs said

Thanks for this great piece of work.
I would be interested in the support of "dependent" forms as you described them above (A and B), too.
Do you plan to add such a feature?

Posted by: cs at February 20, 2007 05:25 PM .

Matthew said

Wonderful script - looking to customise for my particular site.

The script is looking up street names from a DB. Many of the street names are made up of more than one word. eg TRIQ ABBE R. A. DE VERTOT
This makes matching the first character not very useful.

I have my array populated using LIKE %'.$input.'% which populates the main array properly with the street names based on any part string matching.

However, the rest of your script seems to loose these records and only display those matching the first letter onwards.

Any ideas which functions I need to look at to resolve this? if at all possible.

Thanks! Matthew

Posted by: Matthew at February 25, 2007 08:02 PM .

xSquall said

For those still not figure out how to use it with a simple query to Mysql:

test.php


$input = $_REQUEST['input'];
$link=mysql_connect("localhost", "root", "");
mysql_select_db("YourDateBase",$link);
$qr=mysql_query("SELECT id_user,rut_user FROM tbusers WHERE rut_user LIKE '".$input."%'",$link); while($row=mysql_fetch_array($qr)) { $aResults[] = array( "id"=>($row['id_user']) ,"value"=>htmlspecialchars($row['rut_user']), "info"=>htmlspecialchars($row['rut_user']) );
}
header ("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); header ("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); header ("Cache-Control: no-cache, must-revalidate"); header ("Pragma: no-cache");
if (isset($_REQUEST['json']))
{
header("Content-Type: application/json");
echo "{\"results\": [";
$arr = array();
for ($i=0;$i {
$arr[] = "{\"id\": \"".$aResults[$i]['id']."\", \"value\": \"".$aResults[$i]['value']."\", \"info\": \"\"}";
}
echo implode(", ", $arr);
echo "]}";
}
else
{
header("Content-Type: text/xml");
echo "";
for ($i=0;$i {
echo "".$aResults[$i]['value']."";
}
echo "";
}


that's all
.

Posted by: xSquall at February 26, 2007 02:53 AM .

Christine said

Hi I am using your script its really good and I came to ask a question, but I notice Carlo already asked it. I want to do the same thing.. I am sure it must be possible, just not quite sure how yet!

If you've had any further ideas on this one, I'd really appreciate it!

Thanks for a great script

Posted by: Christine at February 26, 2007 07:47 AM .

Christine said

Hi again! Further to my comment yesterday, I just wanted to let you know that I figured out a way to do what I wanted.

In the call where you set up which script to use for the database query, I thought what if I could update this when the first text field (in my case suburb) was updated, so I put an onblur event in the suburb field. The onblur then updates options.script, adding an extra url parameter to the end of the script name with the suburb value.

So the onblur on the additional field in my code looks like this:

onblur="options.script='autosuggest/test.cfm?sub=' + this.value + '&';"

I hope I have explained that clearly enough, because it works a treat!

Cheers
Christine

Posted by: Christine at February 27, 2007 03:12 AM .

bsn said

Hi Christine,

sorry I haven't got around to answering - I'm up to my ears in work at the moment.

Good solution!

I would have suggested rewriting the script so that the "script" argument can be either a string (as it is now), or a function. Before the AJAX request is made, you could retrieve a string from the function passed as the script parameter.

if (typeof(script) == "function")
{
    var myscript = script();
} else {
    var myscript = script;
}

// do ajax request using 'myscript'

Your script parameter could look like this:

var script = function () {
    return 'autosuggest/test.cfm?sub='  ¬
        + document.getElementById('field1').value ¬
        + '&';
}

The difference is that the first field doesn't "know" that the second field is grabbing it's value for it's own purposes, whereas in your version the first field actively changes the parameters in the second.

In practice it doesn't make much difference, only that you are relying on logic attached to field1 for the functionality of field2, which somehow doesn't seem so neat.

Tim.

Posted by: bsn at February 27, 2007 08:16 AM .

John said

Hi, very nice script! Is there an 'easy' way to adopt it such that the result list is display upwards instead of downwards?

Posted by: John at February 27, 2007 02:33 PM .

bsn said

Hi John,

after the list has been appended to the DOM (in the createList function), get its offsetHeight, and set the "top" value of the containing div to the y position of the textfield, minus the height of the list, minus any padding you want.

Getting the y position of the text field is a bit tricky, but lucky the script knows it already: pos.y.

div.style.top = pos.y - div.offsetHeight + "px";

Of course, the pointy thingy at the top of the list should then by rights be at the bottom, but that's a CSS issue.

Tim.

Posted by: bsn at February 27, 2007 02:58 PM .

tinytim said

xSquall said

For those still not figure out how to use it with a simple query to Mysql:


anyone else getting this:
Parse error: syntax error, unexpected ';' in /test.php on line 24

any ideas? php noob....

Posted by: tinytim at February 27, 2007 04:09 PM .

bsn said

tinytim

looking at xSqualls code, it looks as if movable type cut out the "less than" symbols in his "for" loops.

Should read:

for (i=0;i<count($arr);i++)

If you copy xSqualls code, there are two things to consider before using it in a live enviornment:

You are pasting your database username and password into a php file. This file should be as closely protected as possible.

You are injecting unvalidated user variables ($_REQUEST['input']) directly into a mysql query. In this example I could search for "!' OR password LIKE '%a'", and mysql would return all users who have password beginning with 'a', presuming a password column exists.

Not exactly hacking the NSA, but it's still a loophole.

If you are using postgreSQL, the engine allows stacked queries, which makes it possible to delete the whole rut_user table in the example, by searching for

"0'; DELETE FROM rut_user WHERE id_user != '0';"

etc. etc.

MySQL security guidelines. Scroll down to "Do not trust any data entered by users of your applications".

Posted by: bsn at February 27, 2007 04:32 PM .

tinytim said

bsn said

tinytim

looking at xSqualls code, it looks as if movable type cut out the "less than" symbols in his "for" loops.

Should read:

for (i=0;i<count($arr);i++)

If you copy xSqualls code, there are two things to consider before using it in a live enviornment:

You are pasting your database username and password into a php file. This file should be as closely protected as possible.

Thanks for the heads up, I usually use a connect
then hide that file...

Posted by: tinytim at February 27, 2007 04:55 PM .

Grateful Developer said

Thank you Tim! Your code rocks (as always)!

Posted by: Grateful Developer at February 27, 2007 11:49 PM .

Christine said

Hi Tim,

Thanks for your comment and the alternative idea you presented. I am not the greatest at JavaScript, but what you say makes perfect sense and I am not a fan of relying on things like onblur, so I will definately try it your way.

Another question, one of the improvements of this version was "Completes field when enter key is pressed" is it possible/easy to make the field complete when tab is pressed, it's just thats how some other autocomplete boxes on our site work and it would be good to keep the consistency.

Cheers
Christine

Posted by: Christine at February 28, 2007 04:56 AM .

Ray Latchmanan said

Hi Tim,
Thank you for all your time you put into helping all of us. ;-)

I am new to AJAX so, would love to get some assistance from you.

I do not have PHP installed on our environment. But I do have an external XML file with all the information. Example below with tags disabled

How can I use that with your script? Any advise will be greatly appreciated.


[?xml version="1.0" encoding="iso-8859-1"?]
[policies]
[policy]
[title]Absenteeism policy[/title]
[url]/hr/pdl/policies/aaaaa.aspx[/url]
[lastupdated]2006-01[/lastupdated]
[/policy]
[/policies]

Cheers,
Ray

Posted by: Ray Latchmanan at February 28, 2007 07:42 AM .

bsn said

Hi Christine,

easy one. line 141. Replace RETURN with TAB.

Tim.

Posted by: bsn at February 28, 2007 10:18 AM .

bsn said

Hi Ray.

Try this (line 306):

// traverse xml
//
var results = xml.getElementsByTagName('results')[0].childNodes;

for (var i=0;i<results.length;i++)
{
if (results[i].hasChildNodes())
{
this.aSuggestions.push( { ¬
'id':results[i].getAttribute('id'), ¬
'value':results[i].childNodes[0].nodeValue, ¬
'info':results[i].getAttribute('info') ¬
} );
}
}


1. Change the value of 'results' to xml.getElementsByTagName('policies')[0].childNodes;. This will give you an array containing the child nodes of policies.

2. The script then loops through the array. For every element that has 'children' (in this case just the 'policy' elements, the whitespace inbetween is ignored), it creates an object and appends it to the aSuggestions array. Each object has an 'id', a 'value', and an 'info' attribute.

You want something like this:

this.aSuggestions.push(  { ¬
  'id':results[i].getElementsByTagName('url')[0].nodeValue, ¬
  'value':results[i].getElementsByTagName('title')[0].nodeValue, ¬
  'info':results[i].getElementsByTagName('lastupdated')[0].nodeValue ¬
}  );

For each policy element ('results[i]'), we retrieve the value of the first (and, in this case, only) 'url' element ('getElementsByTagName('url')[0]'), and assign it as the id of our autosuggest object. We then do the same for the other two elements, assigning them to 'value' and 'info' repsectively.

The value is the main visible field in the autosuggest, and will be pasted into the textfield when the user selects an item from the list.

Tim.

Posted by: bsn at February 28, 2007 10:48 AM .

Meinhard said

Hi bsn,

your script is very cool - thanks a lot!

How can I handle German umlauts with the latest version? My results are coming from mysql and umlauts are stored correct in the database.

Regards,
Meinhard

Posted by: Meinhard at March 1, 2007 02:14 PM .

bsn said

Hi Meinhard,

Umlauts work for me: try typing "Ä" into the textfield in the example.

Tim.

Posted by: bsn at March 1, 2007 02:22 PM .

Ray Latchmanan said

Hi Tim,
Thank for your codes. Do I have to do any changes on this script? As I mentioned above, I don't have PHP or ASP.net. I have an XML file on the same directory as these files.

[code]

var options = {
script:"test.php?json=true&",
varname:"input",
json:true,
callback: function (obj) { document.getElementById('testid').value = obj.id; }
};
var as_json = new AutoSuggest('testinput', options);


var options_xml = {
script:"test.php?",
varname:"input"
};
var as_xml = new AutoSuggest('testinput_xml', options_xml);

[/code]

Posted by: Ray Latchmanan at March 2, 2007 05:34 AM .

Lynx said

Firstly, what a great piece of code. Was just what I was looking for.

I have a little problem I hope someone can help with.

With all the tests and playing around I did before implementing into another script I never once had any problems (so it could be that something from the new script is conflicting).

Any reason why the background is now breaking out from the box.
eg:- www.mypriceguide.co.uk/images/keywordsuggest.png

Any help or solutions would be great.

Many Thanks,
L.

Posted by: Lynx at March 2, 2007 05:51 AM .

Meinhard said

Hi,

you´re right, in your script "Ädams" works fine because in the test.php it´s coded as "Ädams". But in my msql db it would be coded as "Ädams".
"Günter" appears as "G�nter" in the list. Autosuggest finds it, but displays it wrong.

Any ideas?


Meinhard

Posted by: Meinhard at March 2, 2007 07:27 AM .

bsn said

Hi Meinhard,

Try changing the HTML page encoding to ISO-8859-1 (LATIN 1). Test.php is written in UTF-8, which means it looks like "Ädams" when opened as UTF-8 in a text editor...

Tim.

Posted by: bsn at March 2, 2007 07:36 AM .

Meinhard said

Hi Tim,

thanks a lot, now it works fine. :o)


Regards,
Meinhard

Posted by: Meinhard at March 2, 2007 08:51 AM .

Meinhard said

Hi Tim,

another topic confuses me. Please have a look at the two screen shots:
http://www.karsten-jahnke.de/as1.jpg
http://www.karsten-jahnke.de/as2.jpg

I don´t know where to change the color of the small second line of a result. The CSS gives no hint and the java script seems to highlight only the first line of a result.
In your sample script this problem does not appear because the background is nearly black.

What can I do?


Regards
Meinhard

Posted by: Meinhard at March 2, 2007 12:14 PM .

bsn said

Meinhard,

if you read the description on the demo page you'll see the code the script generates to create a list. The second line is in a "small" element. Search for "small" in the CSS file, and you'll find the colours you want to change.

div.autosuggest ul li a span small
{
font-weight: normal;
color: #999;
}

div.autosuggest ul li.as_highlight a span small
{
color: #ccc;
}

Posted by: bsn at March 2, 2007 02:33 PM .

Zagreus said

I've just discovered this useful tool, but I am having problems getting it to work. I have a test form at:

http://telos.london.edu/ajax/journalTitle.html

,which talks to a script which generates XML from a database e.g.

http://telos.london.edu/cgi-bin/lbs/ajaxJT.pl?jt=journal

, but when I type in the journal title form box, I get a browser javascript error which says:

Line: 309
Char: 3
Error: Object Required

I'm new to all this, any advice?

Posted by: Zagreus at March 2, 2007 04:07 PM .

bsn said

Hi Zagreus,

Your XML isn't valid (not sure why), which means the browser can't parse the XML document.

I'll admit that the error handling isn't very good at this juncture.

Tim.

Posted by: bsn at March 2, 2007 04:25 PM .

Zagreus said

Not valid? Does it need to reference a DTD? I have, at the beginning:



ABA BANKING JOURNAL
ABA JOURNAL

etc etc

It looks correct according to the documentation. hmmh.... Maybe I'll try with JSON.

Stephen

Posted by: Zagreus at March 2, 2007 04:39 PM .

bsn said

looks good to me too, but I ran it through a validator, and it didn't like it.

Another thing: I would only return about the first 30 results via AJAX, otherwise the script is going to try to create a list with about 1000 LIs...

Posted by: bsn at March 2, 2007 04:45 PM .

bsn said

Hi Stephen,

I checked the HTTP headers your server is sending, and you have set the Content-Type to "text/xml", not "text/html".

Tim.

Posted by: bsn at March 2, 2007 04:55 PM .

Zagreus said

Thanks for the replies. I've tried both text/xml and text/html - none seem to have any (positive) effect. I think I'm going to have to think about it over the weekend!!

Posted by: Zagreus at March 2, 2007 05:00 PM .

Christine said

Hello yet again Tim!

Thanks again for your quick responses and being soo helpful. I did as you said to make TAB select a list option, however it then makes the TAB key not work when tabbing between the form elements. Any idea how to have both working?

Cheers
Christine

Posted by: Christine at March 6, 2007 01:36 AM .

JosephPhilbert said

How would use this with "php csv2array"??
$dropdowns=csv2array('config/dropdowns/company.csv');

var options = {
script:$dropdown;
varname:"input",
json:true,
callback: function (obj) { document.getElementById('testid').value = obj.id; }
};
var as_json = new AutoSuggest('testinput', options);

want to add it to my current code.


Posted by: JosephPhilbert at March 6, 2007 04:55 AM .

Zagreus said

I've fixed the issue. Initially I was (using perl) doing:

print "Content-type: text/html\n\n";

, changing it to:

print "Content-type: text/xml\n\n";

didn't work, BUT changing it to the following did:

print "Content-type: text/xml; charset=iso-8859-1\n\n";

It needed the charset value set in the header.

I need to play with the presentation now, and also find the best way of using to use the minChars value. I think I'll I play with my script to only start retrieving XML after I've entered the first word, and set shownoresults to false. Obviously if the title is only one word then nothing will happen, but it seems better that retreiving 2000+ records when the person typing j for "journal of whatever", and slowing things down.

Posted by: Zagreus at March 6, 2007 11:46 AM .

bsn said

Hi Zagreus,

You seem to be doing a LIKE '%input%' query. This is far slower than a LIKE 'input%' query. It would be much faster to retrieve only those results whose first characters match the input. Then I would add an index for the first five characters of the 'title' column (if you haven't already). That should speed things up a lot.

Like I said before, I would limit the number of results returned to 30. Displaying 2000 results in a dropdown isn't helping the user.


Tim.

Posted by: bsn at March 6, 2007 11:55 AM .

Zagreus said

Thanks for the advice bsn. One of the reasons I was doing a LIKE '%input%' in my SQL statement, is to cater for journals like:

"the journal of finance"

. Users never put the word "the" in, and hence are surprised when they find nothing. There are ways of getting around this (changing the data etc) - I think I will resort to using the single wildcard (it does speed things up!), and I'll look into the index idea.

Cheers!

Posted by: Zagreus at March 6, 2007 02:23 PM .

Zagreus said

Sorry, this strictly isn't a Ajax Auto Suggest v.2 question, but CSS is not my strong point and this is driving me mad. I have put Auto Suggest into a test form (based on what I actually want to use it for).The url is:

http://telos.london.edu/ajax/afTest.html

The "Journal Title" field is the only field that is is using AA, so if you start typing something like the word "journal", the list of possible values appear. I have two questions:

1. How can I get this to go (float) over the date drop down boxes? At the moment the values seem to go under them, and the date fields prevent the user from seeing the AA values.

2. Is there a way of getting a border around the AA list? I tried something like:

border: 1px solid #888;

, but I get something like:

----
|A|
----
|B|
---
|C|
---

when I want:

----
|A|
|B|
|C|
----

I was hoping that it would appear in a little box, like a drop down list - self contained. Even using border-collapse:collapse, border-bottom:1px doesn't seem to help. Any tips?

I'm editing the "div.autosuggest ul li a" part of the supplied CSS file. Is this the correct section?

Posted by: Zagreus at March 6, 2007 04:42 PM .

Ryan said

I was wondering if it were possible to use this to generate multiple auto completions in the same text box? For instance: you start typing in a name, the auto complete shows up and you click a name, the name is put into to text box followed by a semi-colon, then you start the process over until all the desired names are filled in.

I would like to use this to allow for users to select names in the database, as well as be able to input names which are not in the database. When they submit, the names that aren't in the database would then be added.

I hope this makes sense.

Posted by: Ryan at March 6, 2007 05:39 PM .

Zagreus said

Just in case anyone has the same problem as I had. (re: point one - the drop down div box going under the select box), apparently it's a know problem with certain versions of IE. There's an article here which describes the problem and a possible solution using an iframe:

http://weblogs.asp.net/bleroy/archive/2005/08/09/422047.aspx

Posted by: Zagreus at March 9, 2007 03:41 PM .

Morgan said

I think your .js conflicts with the Ajax.Updater class. The conflict occurs between lines 647 and 662 of your .js. For example, if I remove these lines of code, one of my functions that uses the Ajax.Updater class runs fine, otherwise I get an error about unkown object.

I've spent a few hours trying to make my code compatible with your .js. However, I still can't get your .js and my function to work on the same web document. I have reason to believe the problem lies in the use of XMLHttpRequest and that your .js overrides the attributes and parameters of my embedded javascript.

Posted by: Morgan at March 9, 2007 09:39 PM .

bsn said

Hi Morgan,

Could well be. I can't guarantee that it'll work with every other js. However, try setting the useBSNns variable to true before you load the AutoSuggest file:

<script type"text/javascript">
var useBSNns = true;
</script>

And create a new AutoSuggest instance using the bsn namespace:

var as_json = new bsn.AutoSuggest('testinput', options);

All functions are then encapsulated in an object called "bsn". Might help.

Tim.

Posted by: bsn at March 10, 2007 08:33 AM .

Morgan said

I solved my problem. I basically adapted my script to use bsn's XmlHttpRequest handling only. The problem was that XHR doesn't like multiple instances firing.

Posted by: Morgan at March 10, 2007 08:35 AM .

Morgan said

Thanks bsn! I haven't tried your solution yet but if it works yours is much cleaner than mine :)

I basically passed my XHR variables to your script's XHR handlers and then created an object in your script to output the results to the DOM.

btw, BSN's great! Thanks!

Posted by: Morgan at March 10, 2007 08:41 AM .

GnunuX said

I found some bugs in your code :

1/ In line 294, if I "backspace" all caracters and more when suggest is display, we have a bug.

And my version of ie 5.0 don't understand push method :

---------------------
if (req.responseText != '')
{
var jsondata = eval('(' + req.responseText + ')');

for (var i=0;i {
if (typeof this.aSuggestions.push != "undefined")
{
this.aSuggestions.push( { 'id':jsondata.results[i].id, 'value':jsondata.results[i].value, 'info':jsondata.results[i].info } );
} else {
var new_arr=new Array( { 'id':jsondata.results[i].id, 'value':jsondata.results[i].value, 'info':jsondata.results[i].info } );
this.aSuggestions=this.aSuggestions.concat(new_arr);
}
}
}
---------------------


2/ At the end of "_bsn.AutoSuggest.prototype.clearSuggestions = function ()", in line 609, I have add this line :

---------------------
this.clearHighlight();
---------------------

3/ For ie5, in line 951 I have replace

---------------------
if (this.ele.filters) // internet explorer
---------------------
with
---------------------
if (typeof this.ele.filters != "undefined") // internet explorer
---------------------

and line 951

---------------------
if (this.callback != undefined)
---------------------
with
---------------------
if (this.callback != "undefined")
---------------------

Now this script is bug free (for me) and works fine on ie5.

Just an tipps, at the end of fonction :

_bsn.AutoSuggest.prototype.setHighlightedValue

I have add that :
---------------------
} else {
if (document.getElementById('name_button')) {
document.getElementById('name_button').click();
}
---------------------

Now, when I press enter and there is no suggestion, "name_button" is submit.

I hope it will help some.

Posted by: GnunuX at March 10, 2007 09:11 PM .

boggins said

Fantastic stuff:-) have adapted to autocomplete addresses, the user can then copy address to other parts of form!

One small quirk, on Firefox the id does not seem to return? Ok on Opera and IE. Keep up the good work!

Posted by: boggins at March 11, 2007 11:13 PM .

boggins said

Sorry, forgot to mention, it is happening via Mysql not on your demo! Probably something I have screwed up.

Posted by: boggins at March 11, 2007 11:18 PM .

boggins said

Now sorted. Was using instead of in input tag, doh!

Posted by: boggins at March 12, 2007 09:35 AM .

boggins said

NAME instead of ID

Posted by: boggins at March 12, 2007 09:36 AM .

BPG said

Is it possible to setup autocomple dependency, so that if I, for example search for a supermarket in the first input form the second input form will only autocomple the city’s where it found a supermarket.
So input1 is independent, input2 is depended and autocomplete’s like “Select * from TABLE where supermaked_id=123 and city like “newy%”
I saw something like this was mention before, maybe someone has a example available?
Thanks in advance and success with this GREAT script!

Posted by: BPG at March 12, 2007 11:13 PM .

Nicolas said

hey, this is a really nice script
i've been looking something like thing long ago!!
i have a question
how do i parse a xml with this structure?


NAME
NUMBER


OTHER NAME
OTHER NUMBER


cheers (and excuse my bad english)

Posted by: Nicolas at March 13, 2007 12:59 AM .

Nicolas said

(i have to remember put preview before anything)
now it's right
the question: how do i parse this xml with your nice script?

<row>
<cell>NAME</cell>
<cell>NUMBER</cell>
</row>

<row>
<cell>OTHER NAME</cell>
<cell>OTHER NUMBER</cell>
</row>

</data>
</root>

Posted by: Nicolas at March 13, 2007 01:05 AM .

Nikos said

Hello

I downloaded the script and it is simply awesome. Big thanks. I was wondering, what do I have to do to achieve the following:

-By clicking on my selection, I cause it to execute the following javascript method:

function refresh_uname()
{
var sURL = "index.php?t=tcre&usern="+escape(document.tcreate.username.value);
window.location.href = sURL;
}

Basically, I want to pass the selected value (the field is called 'username') to the URL.

I tried to use a onChange and call the refresh_uname() method but it only takes the incomplete value. For example, if I type 'Ath' and the value in the Bubble is 'Athens' and I click on it, the onChange when I click on the bubble value will get Ath.

Any help as to what to do here is appreciated. Thanks again for this fantastic script...

Posted by: Nikos at March 13, 2007 04:14 PM .

Ernesto Vargas said

I will like to update 4 more fields with values releted to the selection.

Any ideas?

Posted by: Ernesto Vargas at March 13, 2007 10:27 PM .

matteo said

Someone can help me in bringing google address in autosuggest?
would be great if i can make an autosuggest with address of a city. Address that tell me google maps..

someone can help me?

Posted by: matteo at March 14, 2007 03:02 PM .

Richard Zak said

I am trying to use the code, but including it in my CFM file causes an error in another javascript file: "Ajax.Request is not a constructor". Thoughts anyone?

Posted by: Richard Zak at March 14, 2007 08:45 PM .

XaviGo said

Hi.

I'm using your code, I have 2 input text with autosuggest and a select list.
With Mozilla everything works fine but with IE the second autosuggest fields renders *below* the select list so it's almost invisible.

Do you know how can I force the autosuggest to the forefront in IE??

Posted by: XaviGo at March 19, 2007 11:44 AM .

Becky said

What license terms apply to Ajax Auto Suggest?

Posted by: Becky at March 20, 2007 01:16 AM .

bsn said

Hi Becky,

It's released under a creative commons license.

Don't take the attribution part too seriously. If you do use it, and it's feasable to link back to this page (i.e. you're not building whitehouse.gov, or anything like that), I would obviously appreciate it.

Tim.

Posted by: bsn at March 20, 2007 08:09 AM .

Flow said

Hi all,
A repost of using this awesome script with MySQL. I had problems with the one from xSquall so here you go.
Note: I'm using mysqli instead of mysql.
But chanching it back to mysql is a piece of cake.
Note2: This is just the code above the 4 lines that start with "header". Everything from those lines and below is exactly the same.

[code]
$input = strtolower( $_GET['input'] );

$aResults = array();

$link = mysqli_connect("host", "username", "password", "database") or die(mysqli_connect_error());

$query = "SELECT id,straat_off,woonplaats FROM adreslocaties WHERE straat_off LIKE '".$input."%'"." GROUP BY straat_off,woonplaats LIMIT 20;";

$result = mysqli_query($link,$query);

while( $row = mysqli_fetch_array($result) )
{
$aResults[] = array( "id"=>($row['id']) ,"value"=>($row['straat_off']), "info"=>($row['woonplaats']) );
}

[/code]

Posted by: Flow at March 21, 2007 11:51 AM .

Flow said

And ofcourse it has to go into "test.php"

Posted by: Flow at March 21, 2007 11:53 AM .

Flow said

bsn said

Hi Christine,

sorry I haven't got around to answering - I'm up to my ears in work at the moment.

Good solution!

I would have suggested rewriting the script so that the "script" argument can be either a string (as it is now), or a function. Before the AJAX request is made, you could retrieve a string from the function passed as the script parameter.

if (typeof(script) == "function")
{
var myscript = script();
} else {
var myscript = script;
}

// do ajax request using 'myscript'

Your script parameter could look like this:

var script = function () {
return 'autosuggest/test.cfm?sub='  ¬
+ document.getElementById('field1').value ¬
+ '&';
}

The difference is that the first field doesn't "know" that the second field is grabbing it's value for it's own purposes, whereas in your version the first field actively changes the parameters in the second.

In practice it doesn't make much difference, only that you are relying on logic attached to field1 for the functionality of field2, which somehow doesn't seem so neat.

Tim.

I don't get it. Where does this code go?
How does the first or second field know when it is using the script as a string or as a function?
Could someone post the complete script and tell me where I should put it?

I also presume you have to rewrite the test.php file because the query should change.

Posted by: Flow at March 21, 2007 12:15 PM .

Tom said

Thanks for the script - a huge help and time saver.

I'm having a small issue with the 'shownoresults' option of the .JS file. When set to 'false', it still appears to be showing the 'noresult' line. Is there anyway to fix this?

It occurs in the non-modified version of the script I download as well.

Posted by: Tom at March 22, 2007 08:00 PM .

Bogdan said

Hello Tim and thaks for this wonderful script. Great JOB.
Flow said:

I don't get it. Where does this code go?

How does the first or second field know when it is using the script as a string or as a function?

Could someone post the complete script and tell me where I should put it?

I also presume you have to rewrite the test.php file because the query should change.

Hello Flow: you have to find in bsn.AutoSuggest_c_2.0.js this function and replace that code with this:

_bsn.AutoLocalitate.prototype.doAjaxRequest = function ()
{

var pointer = this;

if (typeof(this.oP.script) == "function")
{
var myscript =this.oP.script();
}
else {
var myscript = this.oP.script;
}
// create ajax request
var url = myscript+this.oP.varname+"="+escape(this.fld.value);
var meth = this.oP.meth;

var onSuccessFunc = function (req) { pointer.setSuggestions(req) };
var onErrorFunc = function (status) { alert("AJAX error: "+status); };

var myAjax = new _bsn.Ajax();
myAjax.makeRequest( url, meth, onSuccessFunc, onErrorFunc );
}

Then you have to replace in the html page:
script:"test.php?",
with:
script:function() {
return 'test.php?id='+ document.getElementById('the_field_you_want').value+'&'
},
Hope this helps. Thanks again Tim.
Bogdan

Posted by: Bogdan at March 23, 2007 02:34 PM .

Larry said

Outstanding work Tim... I'm sure you hear that a lot, but it really is a beacon of quality.. :)

I've found the script to be a little slow compared to others... so wondered if it might be the size of the JS code. Is there anything one can cut out to make it a leaner script. I'm using the XML portion exclusively for instance. Does the JSON code make any improvement to performance?

For the PostgreSQL guys... here's my snippet of code for getting 2 fields from the database. Hope it helps:

("header" stuff as normal follows this)

$input = strtolower( $_GET['input'] );
$len = strlen($input);
$aResults = array();

if ($len)
{
$db = pg_connect('your DB');
$qu = pg_query($db, "your QUERY");

$i=0;
while ($row = pg_fetch_row($qu))
{
if (strtolower(substr($row[0],0,$len)) == $input)
{
$aResults[] = array( 'id'=>($i+1), 'value'=>htmlspecialchars($row[0]), 'info'=>htmlspecialchars($row[1]) );
$i++;
}
}
pg_free_result($qu);
}

Posted by: Larry at March 24, 2007 04:51 AM .

Larry said

Is there a quick & easy way for me to populate a second form field with the 'info' result? I don't want a second auto-complete... just have the info line placed into another form input box when the user selects with the mouse or arrows/enter.

A lot of code to look through is daunting, so wondered if you could spare me some! thanks.

Posted by: Larry at March 24, 2007 05:15 AM .

bsn said

Hi Larry,

the JavaScript shouldn't be noticably slower than other scripts. The AJAX request is probably slowing things up. JSON is quicker than XML, because the filesize is smaller (the ratio of markup to data is higher in XML). How many results are you returning from the database? As I've said before, I would limit the number of results to about 30.

As for using the 'info' part: user a callback function:

var options = {
  script:"test.php?json=true&",
  varname:"input",
  json:true,
  callback: function (obj) { document.getElementById('targetField').value = obj.info; }
};

Tim.

Posted by: bsn at March 24, 2007 12:19 PM .

bsn said

@Flo and Bogdan

I've updated the script to do what you're asking for. You can now set the script value as a function, allowing for autosuggest fields that rely on a selection in a previous field.

Tim.

Posted by: bsn at March 24, 2007 03:45 PM .

Nikos said

Tim

Your updated script (the download) seems to appear in one line in a text editor and makes it extremely difficult to read. Is there a way to have this in a format that doesn't appear in one line only? Thanks in advance

Posted by: Nikos at March 26, 2007 12:02 PM .

bsn said

Hi Nikos,

the other javascript file in the js folder is the uncompressed version.

Tim.

Posted by: bsn at March 26, 2007 12:16 PM .

Marco said

Hi Tim,

Thanks for your script. It works great. The mysql tips and the 2 field problem discussion solved a few of my issues.

I still have a question. Is it possible to activate the script when someone tabs to or clicks in the field? I mean before entering a letter.

Thanks Marco

Posted by: Marco at March 26, 2007 03:03 PM .

Timmy said

Thanks for the great script. I set the length for the list is 25 items. However the length of the list is still long. I set the style for the div is scrollable (overflow: auto). When I use the arrow down button, the div is not scrolling. I may not see the highlighted item. How could I make the list scrolling so I could see the highlighted item by using the arrow key?
Thanks so much for your time.

Posted by: Timmy at March 26, 2007 06:13 PM .

Jared said

Hey Zagreus - did you manage to get it working?
Unfortunately for me I can't get that hack working and thus I can't use this script which is a real shame as I spent time integrating it only to find that once I tested it in IE I saw the bug.

I found this post:
http://weblogs.asp.net/bleroy/archive/2005/08/09/422047.aspx

He apparently fixed it, but I can't integrate it as its beyond me.

This auto suggest is the best I've found so it's just a real shame that apart from this stupid IE bug I can't use it.

If anyone nice has managed to integrate a fix, I'd be extremely grateful ;-)

Thanks - J.

Posted by: Jared at March 26, 2007 08:26 PM .

junkie234 said

Hi.

Is there a way to limit the results in the javascript? When I do it in the mysql query and limit something to 5, the code doesnt work the way i need it to. Ex. I'm looking up things that start with number 881, I hit backspace and write 3 instead of the 1, so new results should show up for 883 but its using the same query as for 881 and i get no results.

Can this be modified in the javascript?

Posted by: junkie234 at March 27, 2007 08:43 PM .

Larry said

bsn said

Hi Larry,

the JavaScript shouldn't be noticably slower than other scripts. The AJAX request is probably slowing things up. JSON is quicker than XML, because the filesize is smaller (the ratio of markup to data is higher in XML). How many results are you returning from the database? As I've said before, I would limit the number of results to about 30.

As for using the 'info' part: user a callback function:

var options = {
script:"test.php?json=true&",
varname:"input",
json:true,
callback: function (obj) { document.getElementById('targetField').value = obj.info; }
};

Tim.

Thanks Tim, it worked a treat... I'm only returning 6 results but the DB has 1.5 million records! Needless to say I'm going to work on making the DB smarter first!

By the way, if the JSON is faster, why would someone choose the XML option? Any disadvantages to JSON for instance?

Thanks again,
Larry.

Posted by: Larry at March 28, 2007 06:03 AM .

Martin said

Hi BSN,

thank your for that great script !

Nearly everything works correct for me except the "hidden field" value, if i get the data via xml.

If I use JSON the hidden value shows up, but not with the XML way.

Thats your example form part with an extra hidden field (JS File and CSS Sheet are allready included, 'useBSNns' is allready set to TRUE):
--------------------------------------------------------------------------

<div>
<form method="get" action="">
<small style="float:right">Hidden ID Field: <input type="text" id="testid" value="" style="font-size: 10px; width: 60px;" disabled="disabled" /></small>
<label for="testinput_xml">Person</label>
<input type="text" id="testinput_xml" value="" style="width:300px" />
<br /><br /><input type="submit" value="submit" />
</form>
</div>

And here your Javapart example
--------------------------------

<script type="text/javascript">
var options_xml = {
script: function (input) { return "test.php?input="+input+"&testid="+document.getElementById('testid').value; },
varname:"input"
};
var as_xml = new bsn.AutoSuggest('testinput_xml', options_xml);
</script>


The Dropdown Listing of the People works, but no ID is shown in the hidden field. Did I do something wrong? Is there maybe a bug in the bsn.AutoSuggest_2.1.js file?

Any idea? Hmmm...

Thank you very much for your script and your help !!!

Martin

 

P.S.: Btw.: Is there any way, how I could change the bsn.AutoSuggest_2.1.js file, so that "info" (i.e. Buckinghamshire) and "value" (Altman, Alisha) are both inserted into the textfield after selecting from the dropdown menu (with the dropdown menu staying like it is). Thaaaanks very much.

Posted by: Martin at March 28, 2007 11:47 PM .

Drakkhen said

Hi

I have read all the message from both version and I feel a little stupid.

What I want is really simple.

When the text form has been filled with autosuggest, I just want to submit and go to the page I want with the ID !
How do I decide which ver is transmitted with the form.

thx

Posted by: Drakkhen at March 29, 2007 06:12 PM .

BPG said

Thans again for the great script and the possabilty for dependancy! Unfortunitly i can't get the las one going, can someone please tell me what i;m doing wrong?

// First Field
var options = {
script:"test.php?json=true&",
varname:"input",
json:true,
callback: function (obj) { document.getElementById('testid').value = obj.id; }};
var as_json = new AutoSuggest('testinput', options);
// Second field, dependend onnumber one
var options = {
script: function (input) { return "test.php?json=true&input="+input+"&testid="+document.getElementById('testid').value; },
//script:"test.php?json=true&",
varname:"testen",
json:true,
callback: function (obj) { document.getElementById('testid1').value = obj.id; }};
var as_json = new AutoSuggest('testinput1', options);

Posted by: BPG at March 29, 2007 08:33 PM .

Drakkhen said

@ BGP

If I may.
I have read so much this thread that I know why it won't work.

You initialize twice the same var.
You have to create a different var
//first field
var options1 {...}
var as_json1 = new AutoSuggest('[ID field1]', options1);
// second field
var options2 {...}
var as_json2 = new AutoSuggest('[ID field2]', options2);

Hope it will help you.
If you have an idea for my problem, your welcome ;)

Posted by: Drakkhen at March 30, 2007 09:57 AM .

BPG said

Thanks Drakkhen, it didn't instantly fix my problem, but it got me thinking :o, now I’s fixed :) (also made an error in my PHP code)

Accidently i ran into a solution for your question (I’ll guess be course your question itself isn’t quite clear to me), anyway’s, when I switched the id and type field in the script, on select in auto complete the ‘cityname’ (in my case) was replaced by it’s id in the input field
// options
var options3 = {
script:"autocomplete.php?json=true&",
varname:"wieinput", // “input field”
json:true,
callback: function (obj) { document.getElementById('wieid').value = obj.id; } // “id field”
};
var as_json3 = new AutoSuggest('wieid', options3); // “id field” instead of the usual “input field”
// input field
// my “id field”
//
// my “input field”
//

Posted by: BPG at March 31, 2007 01:31 PM .

zhouxuan said

Hi,

I want to change the style of the result list.The info result is under the user result as default,such as the "Buckinghamshire" is displayed under the "Altman, Alisha" in the Demo page.Now I hope to display these two on one horizontal line,The user result by the left and the info result by the right.How can I do this?Thanks vary much.

Posted by: zhouxuan at April 1, 2007 07:17 PM .

aSeptik said

Hi bsn! ;D

Just little problem! ;D after many times i still have problem to retrieve array from database! i have also tried the xSquall and Flow ways but without result! :(

Can you show me the right way! pls, pls! :D

tnx and good job!


PS: very great script! ;D

Posted by: aSeptik at April 2, 2007 02:15 AM .

Lyubomir Petrov said

Just wanned to note that the design of the box is a lil' buggy in Opera :)

Posted by: Lyubomir Petrov at April 2, 2007 08:51 PM .

Alex said

I have a form with two radio button and a text field.
I would like that the javascript auto-complete from a different php file if one of the radio button is checked.
I tried this but it doesnt work, its always the file1.php that is sendind results, even if bt2 is checked:


if (document.getElementById("bt1").checked == true) {
var options = {
script: "file1.php?",
varname: "input",
json: true
};
} else {
var options = {
script: "file2.php?",
varname: "input",
json: true
};
}
var as = new AutoSuggest('search', options);

any ideas ? plz

Posted by: Alex at April 3, 2007 12:44 AM .

Lee said

Hi BSN,
I posted earlier that I really enjoyed your script but I ran into a problem... I don't see my comment approved though :( My last post was a little lengthy but I'll make it short.

Is there a conflict with Prototype? I get a javascript error when I use both of them together.

Posted by: Lee at April 3, 2007 04:53 AM .

Sanjay said

Hello Everybody,
I have been trying to configure this beautiful piece of code using ASP. But i am getting error.Please have a look at my code and help me. I have replaced opening and closing tags with ( and )

****bsn.AutoSuggest.html****

(html)
(head)
(title)Ajax auto-suggest / auto-complete | BrandSpankingNew(/title)


(script type="text/javascript" src="js/bsn.AutoSuggest_c_2.0.js")(/script)

(link rel="stylesheet" href="css/autosuggest_inquisitor.css" type="text/css" media="screen" charset="utf-8" /)

(/head)
(body)

(div id="wrapper")
(div id="content")

(h2)Example (XML)(/h2)

(div)
(form method="get" action="")
(label for="testinput_xml")Person(/label)
(input type="text" id="testinput_xml" value="" style="width:300px" /)
(br /)(br /)(input type="submit" value="submit" /)
(/form)
(/div)
(script type="text/javascript")


var options_xml = {
script:"test.asp?",
varname:"typing"
};
var as_xml = new AutoSuggest('testinput_xml', options_xml);
(/script)

(/body)


****test.asp****
(%
typing = LCase(Request("typing"))

Set objconn=server.createobject("adodb.connection")
objconn.open "Provider=sqloledb;Server=Servername;Database=DBName;UID=sa;PWD=pwd;"
set objrecord=server.createobject("adodb.recordset")


set objrecord=objconn.execute("SELECT TOP 10 records FROM tablename WHERE CHARINDEX ('"&typing&"', records)) 0 ORDER BY CHARINDEX ('"&typing&"', records)")

if objrecord.eof or objrecord.bof then

Response.Write "Oops Not Found"
response.end
else

end if

Response.ContentType = "text/xml"

Response.write "(?xml version=""1.0"" encoding=""utf-8"" ?)(results)"
do while not objrecord.eof
i=i+1
Response.write "(rs)"&objrecord.fields("Vilname")&"(/rs)"
objrecord.movenext
loop
Response.write "(/results)"

%)

Posted by: Sanjay at April 3, 2007 09:28 AM .

Harrison said

Hi, BSN.. Your script really help me a lot in my project, I would like to say thank on your efforts :-)

Well, I have another small question, if wnat the script do something when visitor click and select a choice from the drop down list? for example loading a product information?

One more thing, may I know what is the hidden ID use for?

Thank you

Posted by: Harrison at April 7, 2007 06:38 AM .

h4bib said

Is there a conflict with Prototype? I get a javascript error when I use both of them together....

:(

what to do?

Posted by: h4bib at April 10, 2007 04:09 PM .

angel said

Hi,

I would like to suggest to use encodeURI() instead of escape() function for creating the HTTP request.
The escape() doesn't convert characters like 'ý' to unicode.

angel

Posted by: angel at April 13, 2007 01:01 AM .

Almas said

I've created a scrolling auto-suggest box (div).

file: bsn.AutoSuggest_c_2.0.js,
in "_bsn.AutoSuggest.prototype.createList = function(arr) {}"

add these lines after "div.style..." lines:
div.style.height = "100px";
div.style.overflow = 'auto';

and replace "_bsn.AutoSuggest.prototype.changeHighlight = function(key) {}" function with this:

_bsn.AutoSuggest.prototype.changeHighlight = function(key)
{
var list = _bsn.DOM.getElement("as_ul");
var div = _bsn.DOM.getElement(this.idAs);

if (!list)
return false;

var n;

if (key == 40)
n = this.iHighlighted + 1;
else if (key == 38)
n = this.iHighlighted - 1;

if (n > list.childNodes.length)
n = list.childNodes.length;
if (n n = 1;

if (key == 40 && n > 1)
div.scrollTop = div.scrollTop + list.childNodes[n-1].scrollHeight;
else if (key == 38 && n div.scrollTop = div.scrollTop - list.childNodes[n-1].scrollHeight;

this.setHighlight(n);
}

Then if you hit down or up arrow your auto-suggest box will scroll up and down.

Posted by: Almas at April 14, 2007 10:56 PM .

satya said

thanks for writing a very nice code .
it is working on Firefox and IE when i use
html
only here some code for auto
html
but i am using W3C ORG standard like
DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"
html xmlns="http://www.w3.org/1999/xhtml"
here some code for auto suggest
html
then it isnot working on IE good way .

problem is Div create space between to div and remove.

Can u please tell ywhy it create space in between div.

Thnkas in advance.

Posted by: satya at April 18, 2007 07:33 AM .

Leo said

Hi, firstly this is a brilliant piece of coding. Thanks a lot.

I have managed to get it set up and working perfectly in firefox but when i try it in safari nothing shows up at all. Any ideas what may be causing this?

the code i use is:


var options = {
script: "auto.php?",
varname: "input",
};
var as = new AutoSuggest('searchInput', options);

If you can help i will be eternally gratefull

cheers

leo

Posted by: Leo at April 20, 2007 10:46 PM .

Jean said

I too think this is a great script, but I have the same problem as some others do, it isn't compatible with other prototype dependent scripts.

It starts at/around line 623 (not sure the exact line, as I made some changes myself).

"// AJAX PROTOTYPE".

I think the problem is that you use _bsn.Ajax to create prototype functions. This way it "overwrites" the use of Ajax.Request for example.

I'm narrowing down the error and see if I can fix it myself, but I'm no JS guru, I'm just a PHP programmer who likes to get involved in the "client side hype" :)

Posted by: Jean at April 21, 2007 12:16 AM .

Jean said

Well, that went a lot faster than I expected. To all those who have the same problem as I described in my above post, just rename all instances of _bsn.Ajax to something like _bsn.Ajax2...

Posted by: Jean at April 21, 2007 12:21 AM .

bsn said

Hi Jean, and to everyone that's having compatibility problems with Prototype or other libraries: You can solve the problem even faster.

Before you load the Autosuggest .js, set the following value to 'true':

useBSNns = true;

This shifts the whole code into the 'bsn' namespace. You then create a new autosuggest as follows:

var as = new bsn.AutoSuggest('idOfTextfield', options);

Undocumented functionality. Sorry.

Tim.

Posted by: bsn at April 21, 2007 08:25 AM .

bsn said

@Leo:

the extra comma after "input", perhaps?

Tim.

Posted by: bsn at April 21, 2007 08:26 AM .

Ebrahim said

Hi, I have used the code and it was complete and without any lack.

But as I've used it with my own css file there was problems in the whole structure,for example not showing the

  • s correctly and all the view is not suitable,
    It may not mean of ajax or javascript, my problem is with css files and I want to ask if is it possible to make the css tags specially for the textbox and not active for the other parts of the page.
  • thanks alot

    Posted by: Ebrahim at April 21, 2007 09:16 AM .

    Jean said

    I'm having trouble getting the json structure to show correctly. The document says it should look like:

    { results: [
    	{ id: "1", value: "Foobar", info: "Cheshire" },
    	{ id: "2", value: "Foobarfly", info: "Shropshire" },
    	{ id: "3", value: "Foobarnacle", info: "Essex" }
    ] }
    

    but when I look in firebug I get these results (look at the unwanted quotes):

    {"results": [{"id": "1", "value": "Jean Mertz", "info": ""}, {"id": "47", "value": "Jenkins, Merrill"
    
    

    , "info": ""}]}

    I'm not sure if this is a problem, since the results are still shown, but when I select a name from the list it parses the ID in the textfield, instead of the VALUE. I checked the JS but couldn't find anything. Any suggestions?

    Posted by: Jean at April 21, 2007 12:54 PM .

    Jean said

    On top of my previous question, would it be possible to make the first found autosuggest snap to the onkeydown for the ENTER/RETURN key?

    When using this nifty script my feeling always makes me hit enter whenever I have the desired result on the first place, however, right now you have to click on it or hit the arrow-down key first to select it.

    Posted by: Jean at April 21, 2007 01:19 PM .

    Lee said

    Hi,
    Does anyone know how to make the autosuggest width a little bigger? My input field is kind of small, and so I would want the width to be about 200%.

    Along those lines--has anyone made any other sets of CSS rules for the autosuggest? I really like the CSS as it is, but it doesn't match my own scheme.

    Thanks!

    Posted by: Lee at April 21, 2007 08:33 PM .

    Jean said

    Lee,

    Look around the line 440 for this comment:

    // get position of target textfield
    // position holding div below it
    // set width of holding div to width of field

    You'll find your answers there ;)
    Also, about the css styles. I made mine a bit more simplistic and less intrusive. (click)

    Posted by: Jean at April 22, 2007 12:27 AM .

    Ebrahim said

    I can't use it in combination of other CSS files,
    how can i preform it to be applicable with every file,
    How can i use it with different CSS file and not mixed with my other HTML element?

    thanks

    Posted by: Ebrahim at April 22, 2007 03:55 PM .

    Lee said

    Jean, that worked perfectly, thanks!

    I changed the left boundary and width accordingly. I wonder if I could introduce more options that could be used like this.oP.offsety in the excerpt below?


    // get position of target textfield
    // position holding div below it
    // set width of holding div to width of field
    //
    var pos = _bsn.DOM.getPos(this.fld);

    div.style.left = (pos.x-this.fld.offsetWidth/2) + "px";
    div.style.top = ( pos.y + this.fld.offsetHeight + this.oP.offsety ) + "px";
    div.style.width = (this.fld.offsetWidth*2) + "px";

    Posted by: Lee at April 23, 2007 06:16 AM .

    namotco said

    I have a form with the ability to dynamically add more text boxes. How can I use auto suggest with them?

    Posted by: namotco at April 24, 2007 01:24 AM .

    namotco said

    How can I make it work with a text area?

    Posted by: namotco at April 24, 2007 07:49 PM .

    George Verras said

    Hi Tim,
    I adapted your AS V2 code to work with my legacy ASP app. It is Wonderful!! I am using it to create a list, limited to 10 rows of the names of Client Offices that match the textbox input. I'm using SQL Server on the back end to provide an XML data stream back to the AJAX control. Works like a charm! ( I would be happy to share with anyone how I did this) I did find this little bug... because I'm searching through so many records it can on occasion hang the webpage if I type too slow or if I backspace. I would like to put a spinning "busy" gif at the end of the text box while the backend is searching for records with the ability to click on it to stop and reset the AJAX control. How would I use the AS code to control a progress bar or spinning gif while the XMLHTTP Request is busy?.

    Posted by: George Verras at April 26, 2007 07:21 PM .

    Lee said

    George,
    you can use the callback parameter to call a function that would control that behavior. The variable obj contains the variables from your xml or json file (info, id,value).

    var options={
    script:something.asp,
    callback:function(obj){yourfunction(obj.id,'busy.gif')}
    };

    Posted by: Lee at April 27, 2007 06:06 AM .

    Civik said

    Hello BSN,
    I have problems integrating this .js in others forms, an error appear when in an HTMl use prototype.js and bsn.autosuggest. A constructor problem appear.

    What could be ?

    Posted by: Civik at April 27, 2007 11:55 AM .

    WDPX said

    What a great pice of work. I already implemented in our content-management-system Aiyoota!-CMS (www.aiyoota.com) for the use of our customers. I had searched for a good auto-suggest-script, but yours seemed the nicest and the easiest to implement. I´m using it for eCommerce products by breaking up the names, but I´m wondering wheater this could work with different parts of the words
    I have something like:
    Summer night gown
    What if someone chose to search for "summer gown"? Your script won´t be able to find that, right?

    Thanx for the work so far and for charing it with us.

    WDPX

    Posted by: WDPX at April 30, 2007 05:38 PM .

    Saurabh Singh said

    Hi,

    I love this script. Specially the css and the inquistor style.

    I have a problem with IE 6. There are SELECT fields right below the text box used for autosuggest.

    If u cud add or guide me in the right direction on how and where to set the visibility of SELECT to hidden before autosuggest shows the suggestion and set them to visible after suggestion are cleared.

    Thanks for the script
    !!

    Posted by: Saurabh Singh at May 1, 2007 03:24 PM .

    Jake H said

    I don't understand why the drop down closes automatically. It is very disconcerting from a user experience perspective. Can I set the timeout to 0 to prevent this?

    Posted by: Jake H at May 2, 2007 11:27 PM .

    D said

    HI George:

    can u send me the ASP Code please, i like to incorporate in my webpage. thanks in advance.
    --------------------------------------------
    George Verras said
    Hi Tim,
    I adapted your AS V2 code to work with my legacy ASP app. It is Wonderful!! I am using it to create a list, limited to 10 rows of the names of Client Offices that match the textbox input. I'm using SQL Server on the back end to provide an XML data stream back to the AJAX control. Works like a charm! ( I would be happy to share with anyone how I did this) I did find this little bug... because I'm searching through so many records it can on occasion hang the webpage if I type too slow or if I backspace. I would like to put a spinning "busy" gif at the end of the text box while the backend is searching for records with the ability to click on it to stop and reset the AJAX control. How would I use the AS code to control a progress bar or spinning gif while the XMLHTTP Request is busy?.

    Posted by: George Verras at April 26, 2007 07:21 PM

    Posted by: D at May 3, 2007 10:41 PM .

    Beefo said

    Hey !

    this script is just GREAT !!!

    I still have things I can't make it run though !

    1. I've a callback functions which is
    callback: function(){document.searchform.submit();}
    My form is called "searchform"...this works just fine if i use the arrow and the enter keys but not if I use the mouse and click...

    2. Way uncool... the list of results is always everything...wathever I type... did i miss something ?

    thanks guys

    beefo

    Posted by: Beefo at May 10, 2007 06:23 PM .

    Beefo said

    Hey Tim,

    Well, I still have my two first problems but after a few checks, here is what I have found.

    My "minchars" is 1 by default, if i type 1 chars, I'll get the suggest but then I get the whole list, if I type a 2nd chars, I get the perfect suggestions. I've tried asking a minchars of 2, but then the correct suggestions is coming only after the 3rd chars !!

    You can try it here: www.sony-center.be/louise/fr/
    Only after you get the temporary cookie that allows you to make it run: www.sony-center.be/temp.cfm

    thanks for your help

    beefo

    Posted by: Beefo at May 11, 2007 12:09 PM .

    David said

    Hello Tim,

    Thanks for the script and it's cool look. Actually I am having a problem as Drakkhen did. I would like to submit the example form but neither of the inputs get submitted. So if I select Davis, Palmer with ID: 27 (that shows up), nothing is transferred to the next page. Any idea what is wrong?

    Thanks again,
    D.

    Posted by: David at May 17, 2007 12:43 AM .

    rinsad said

    Hi BSN

    Could you tell me how your code can be used to iterate through the full result set dowloaded once. Your demo example always make a request to the server. What I prefer is to get the data once and use it many times.

    Thanx

    Posted by: rinsad at May 17, 2007 05:09 PM .

    Seth said

    Does anyone have a converted copy of this for ASP.NET? I saw a comment for the 2.0 version from John West descriving how to convert it, but I can't seem to get it to work. Anyone have something I could use? I'm looking at integrating this with an existing .NET web application for the next iteration.

    Thanks!

    Posted by: Seth at May 18, 2007 10:04 PM .

    puccacita said

    porfavor puede ensenarme auto suggest con data Mysql o mejor con example auto suggest mysql

    include("connect.php");
    connect_db();

    $aUsers = array();
    $aUsers = 'a';
    $rows = array();
    $cou = 0;
    $test = mysql_query("SELECT khongdau from music");
    while($row = mysql_fetch_array($test))
    {
    $rows[$cou] = $row[0];
    $cou++;
    if($cou echo $row[0];
    }
    //echo $rows[2];

    not working :(

    Posted by: puccacita at May 19, 2007 07:38 PM .

    ansh said

    hello ,
    plz help me i want to use this retrive data from mysql field not from XML file.. can anyone tell me how to do it?
    Thanks

    Posted by: ansh at May 20, 2007 09:04 AM .

    John Smart said

    Thank you for this phenominal script - exactly what I needed, wrapped in clean code. I can php and MySQL very well, but JS/Ajax are new to me, as is ( to a lesser extent) xml.
    In customizing the script, I had the hardest time making it work - I woould love to use the json one, because having the field auto fill with the uid is very useful to me - however, in rewriting the php file to produce the output, I always got errors. In the end, I gave up! I use the xml version, and it works beautifully. I guess I can just have the uid show in the extra information. In fact, that will be perfect for what I am doing - in asking the question, I answered it! How cool!
    For the person who posted above me, mnaybe this will help. You will have to use the xml version, and add a sql call that will loop through populating the rss stuff, but to save you my headaches, here is the code I created - please be aware this is very badly hacked together for testing, but it gives the foundation for something much better! - in fact, this just generates a static result, you would need to wrap the tags in a mysql search where whatever LIKE "$_GET[input]"

    header ("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); // Date in the past
    header ("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); // always modified
    header ("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
    header ("Pragma: no-cache"); // HTTP/1.0
    header("Content-Type: text/xml");
    echo'XML Header line here - this software strips it out, just copy from the code you downloaded ';
    $display='';
    #loop throuhg search results
    foo
    baa
    # end loop
    $display.='';
    echo $display;


    Again, thank you so much for such a wonderful script - I regret that I lack the understanding to use it to its fullest extent!

    Posted by: John Smart at May 29, 2007 10:53 PM .

    John Smart said

    This is a very basic piece of code that may help someone get going. Have the script point to this file


    header ("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); // Date in the past
    header ("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); // always modified
    header ("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
    header ("Pragma: no-cache"); // HTTP/1.0
    header("Content-Type: text/xml");
    echo'';# this is the xml version and encoding tag - I am unable to psost that here, so copy the one from the downloaded file.
    include 'includes/config.inc.php';
    # We are to select what we want, and represent it as:
    #foo
    # Test for completness
    $limit=2;
    $tested=$_GET[input][0].$_GET[input][1].$_GET[input][2];
    if (strtolower($tested)=='the')
    {
    $limit=5;
    }
    if (strlen($_GET[input])>$limit)
    {
    #
    $sql='SELECT * FROM artist WHERE name LIKE "%'.$_GET[input].'%"';
    $result = @mysql_query($sql,$connection) or die ('Issues with artist '.$sql);
    while ($row = mysql_fetch_array($result))
    {
    $display.=''.$row[name].'
    ';
    }
    #
    }
    echo''.$display.'';
    ?>

    This limits the search to three characters UNLESS the 1st three characters are 'the' - because that could get messy - this is to list artists from a sql database. The missing include file simply sets the sql connection details. This is a very sloppy bit of code. When I get it tidied up I will resubmit it. If you tinker, and see javascript errors, then you have a php error! It is shown as a javascript error because the java script cannot handle a php error (I know how it feels!)

    Again, than you for supplying this code, I could not have written it, and see uses for it in almost every site I work on!

    Posted by: John Smart at May 30, 2007 03:48 AM .

    John Smart said

    I am using brackets '()' to mark the tags, so they do not get stripped out - I apologize for the repetition.

    Maybe admin can delete the above post?
    This is a very basic piece of code that may help someone get going. Have the script point to this file

    (php#(had to remove the question mark to post this)
    header ("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); // Date in the past
    header ("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); // always modified
    header ("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
    header ("Pragma: no-cache"); // HTTP/1.0
    header("Content-Type: text/xml");
    echo'(?xml version="1.0" encoding="utf-8" ?)';# this is the xml version and encoding tag - I am unable to psost that here, so copy the one from the downloaded file.
    include 'includes/config.inc.php';
    # We are to select what we want, and represent it as:
    #(rs id="1" info="stuff")foo(/rs)
    # Test for completness
    $limit=2;
    $tested=$_GET[input][0].$_GET[input][1].$_GET[input][2];
    if (strtolower($tested)=='the')
    {
    $limit=5;
    }
    if (strlen($_GET[input]))$limit)
    {
    #(SQL wrapper)
    $sql='SELECT * FROM artist WHERE name LIKE "%'.$_GET[input].'%"';
    $result = @mysql_query($sql,$connection) or die ('Issues with artist '.$sql);
    while ($row = mysql_fetch_array($result))
    {
    $display.='(rs id="'.$row[uid].'" info="Date of formation: '.$row[formedmonth].'/'.$row[formedyear].'")'.$row[name].'(/rs)
    ';
    }
    #(/SQL wrapper)
    }
    echo'(results)'.$display.'(/results)';
    ?)


    This limits the search to three characters UNLESS the 1st three characters are 'the' - because that could get messy - this is to list artists from a sql database. The missing include file simply sets the sql connection details. This is a very sloppy bit of code. When I get it tidied up I will resubmit it. If you tinker, and see javascript errors, then you have a php error! It is shown as a javascript error because the java script cannot handle a php error (I know how it feels!)

    Again, than you for supplying this code, I could not have written it, and see uses for it in almost every site I work on!

    Posted by: John Smart at May 30, 2007 03:52 AM .

    karl said

    Here is what a i did (in test.php) to use MySQL, and multiple autocomplete inptus with different tables.

    $link=mysql_connect("localhost", "root", "pwd");
    mysql_select_db("YourDateBase",$link);

    $qry = strtolower( $_REQUEST['input']);

    $field = $_REQUEST['field'];
    $table = $_REQUEST['table'];
    if($_REQUEST['info']) { $with_info = ",".$_REQUEST['info']; $info = $_REQUEST['info']; }

    $string_qry = "SELECT $field $width_info FROM $table WHERE $field LIKE '$qry%' LIMIT 0,20";
    $result = mysql_query($string_qry, $link);

    header("Content-Type: text/xml");

    //Can't post it right, so just check the xml, results and rs tags
    echo "xml version=\"1.0\" encoding=\"utf-8\">results>";

    $i = 0;
    while ($rowdata = mysql_fetch_array($result)) {
    echo "rs id='$i' info='".utf8_encode($rowdata[$info])."' >".utf8_encode($rowdata[$field])."/rs>";
    $i++;
    }
    echo "/results>";

    Now on the html y use 2 inputs:

    //One without info description
    var options_xml = {
    script: function (input) { return "test.php?input="+input+"&testid="+document.getElementById('testid').value+"&field=name&table=customer_contacts"; },
    varname:"input"
    };
    var as_xml = new bsn.AutoSuggest('input_id1', options_xml);

    //And one with info description
    var options_xml = {
    script: function (input) { return "test.php?input="+input+"&testid="+document.getElementById('testid').value+"&field=company&info=mail&table=customers"; },
    varname:"input"
    };
    var as_xml = new bsn.AutoSuggest('input_id2', options_xml);

    Posted by: karl at May 31, 2007 07:55 PM .

    Kieran said

    I have this working now, and it's really good! However, the XML needs to include the XHTML declaration if you need to display any entities other what is included in base XML (quot,amp,apos,lt and gt). This way if you have the true character in MySQL using the UTF-8 encoding, it will match é as if it was a regular e, for example. Then when you run htmlentities on that, everything works beautifully!

    Posted by: Kieran at June 1, 2007 08:38 AM .

    Gordon Thompson said

    Hi,

    This is a great product but I think there are memory leaks, at least on IE. Has anybody come across this?

    Cheers

    Posted by: Gordon Thompson at June 1, 2007 05:36 PM .

    Richard said

    Hello!

    This works great in Firefox!
    I couldn't get it to work in IE though :(
    I have two fields on the page (soon to be three), that needs the auto suggest.
    When typing in IE, I just get a javascript error. (Maybe because of the callback function I put inside the script?

    I couldn't get norwegian characters to work either.. Shows up as question-marks in firefox.. I tried to change the charset to iso-8859-1 but it didn't work.

    Any ideas? If you like, you could take a look at the page. http://ny.waypoints.no/index.php?show=addwaypoint

    Try typing "S" in "Kommune". The entry that shows up as "S?rum" should be "Sørum"

    Posted by: Richard at June 5, 2007 05:22 PM .

    Mer said

    Great script, it was really helpful. I have a question though, I know people asked you that before, in many different ways, but I'm not sure how to apply it to my problem. I have a database with two attributes: Name and Abbreviation. When I select an option from the autosuggest I want the Abbr field to be filled automatically. Is that possible? What do I need to do in the JavaScript and the PHP to make that happen. I don't know much about JS, so it is really hard for me to just look at the script and figure it out on my own.

    Thanks so much

    Posted by: Mer at June 5, 2007 05:54 PM .

    Mer said

    I also have another question. I wanted to have multiple options in one text field separated by commas. So every-time after a comma the autosuggest will pop up again. I that possible? Is that something in the JS or the PHP?

    Thanks again

    Posted by: Mer at June 5, 2007 08:29 PM .

    Gordon Thompson said

    With regards to the memory leaks that I found in IE; I think it's down to the onmouseover/onmouseout event, commenting them out seriously reduces the leaks. It's not a major problem for me as we don't use the mouse for selection but it might help somebody else to fix the problem properly...

    Cheers

    Posted by: Gordon Thompson at June 7, 2007 12:57 PM .

    Maurits said

    Almas said

    I've created a scrolling auto-suggest box (div).

    file: bsn.AutoSuggest_c_2.0.js,
    in "_bsn.AutoSuggest.prototype.createList = function(arr) {}"

    add these lines after "div.style..." lines:
    div.style.height = "100px";
    div.style.overflow = 'auto';

    and replace "_bsn.AutoSuggest.prototype.changeHighlight = function(key) {}" function with this:

    _bsn.AutoSuggest.prototype.changeHighlight = function(key)
    {
    var list = _bsn.DOM.getElement("as_ul");
    var div = _bsn.DOM.getElement(this.idAs);

    if (!list)
    return false;

    var n;

    if (key == 40)
    n = this.iHighlighted + 1;
    else if (key == 38)
    n = this.iHighlighted - 1;

    if (n > list.childNodes.length)
    n = list.childNodes.length;
    if (n n = 1;

    if (key == 40 && n > 1)
    div.scrollTop = div.scrollTop + list.childNodes[n-1].scrollHeight;
    else if (key == 38 && n div.scrollTop = div.scrollTop - list.childNodes[n-1].scrollHeight;

    this.setHighlight(n);
    }

    Then if you hit down or up arrow your auto-suggest box will scroll up and down.

    I tried to make it scroll but it doesn't work, firebug gives errors after if (n
    n = 1; can somebody help me..

    Posted by: Maurits at June 13, 2007 02:27 PM .

    Robert said

    This question was more or less asked previously by "Matthew at February 25, 2007 08:02 PM" but I didn't see an answer and I wondered if there was one. I've set up a demo where the match (on the server) is based on like %input% (i.e. contains, not starts with). This does actually seem to work some of the time, but as youe type the input, it sometimes (correctly) displays all matches containing the text, and sometime only displays the matches at which start with the text. If you go to:
    http://test.bookassist.com/chose_hotel.jsp
    then type "Petit Palace", you may have to delete and retype the words, I think you'll see what I mean.

    Thanks
    Robert

    Posted by: Robert at June 14, 2007 07:41 AM .

    Doron said

    First I want to say YOU ROX !
    I added new option for myself that i would like to share.
    I wanted the first item to be selected automaticly.
    Replace
    this.iHighlighted = 0;

    With
    if(this.oP.highlightfirst)
    {
    this.iHighlighted = 1;
    this.setHighlight(1);
    }
    else
    this.iHighlighted = 0;

    And at the option just use
    highlightfirst: true,

    Thx for this great Auto Suggest.

    Posted by: Doron at June 14, 2007 10:14 AM .

    Alex P'ng said

    Thank you! Thank you! Thank you!

    I've been looking for something like this for over a bloody week.

    Thanks again.

    Posted by: Alex P'ng at June 14, 2007 06:14 PM .

    Ben said

    I've changed php script that returns values from dbms and put them in xml file. Everythings works fine in Firefox or Opera, but IE doesn't.
    What's the problem?
    Even IE gets right number of data "rows" but their values are missing. As I sad, FF and Opera works fine.

    I hope there is a some solution

    Posted by: Ben at June 15, 2007 12:02 PM .

    John G said

    Hi,

    My tips for using PHP/Mysql - A large lookup dataset causes speed and display problems so limit result to say 10 records. For speed, use WHERE (whatever field) >= 'value'. This is faster than LIKE due to MySql indexing not applicable when using LIKE.

    If you have limited to 10 but you then want to get an ID for the hidden field that represents the row position in relation to all records not just the 10 displayed: (Mainly for search forms)

    Generate an array of all values from your main query that just contains the primary record ID. Store array in a session variable.

    In the demo code for this script that generates the XML by looping through the 10 item array - use array_search to search the stored array for the array key that corresponds to each item. Use this key as your ID.

    Use option to call back the ID. The result is you now have the array key of the position of the record in relation to the entire dataset in your main query.

    This can be used for data retrieval, pagination etc.

    JG


    Posted by: John G at June 20, 2007 01:58 AM .

    John G said

    Hi,

    Is anyone using this script with form fields that are contained in an ajax generated popup? Can't seem to get it working.

    JG

    Posted by: John G at June 20, 2007 02:00 AM .

    the_groomedmonkey said

    Just quick note (this is on Mac - funny have to specify now with safari): works fine in Safari 2, firefox 2.0.0.4, but breaks in Opera 9.21 (Mac). It's still functional but the hover becomes quite dissapointing.

    Small concern given its market share, although its my browser of choice when Im not coding.

    tGM

    Posted by: the_groomedmonkey at June 21, 2007 04:43 AM .

    skiloup said

    I extracted the zip and opened bsn.AutoSuggest_2.1.html, and it pops the alert for 'Ajax error'. I just wanted to verify that it worked initially before I add what I need to add. Is there something else I need to do to demo this thing 'out of the box' ?

    Tried in FF & IE

    Thanks much!

    Posted by: skiloup at June 21, 2007 05:25 PM .

    Ken said

    I just implemented your script on http://zoek.net/, but it only seems to work in IE, not in FireFox. I noticed that the example on your site works in both browsers though... Do you have any clue as to what could be causing this?

    Posted by: Ken at June 22, 2007 01:01 AM .

    yacatl said

    Hi.

    First at all, Thanks for this great job.

    I started to read the comments looked up for my answer, but there are to many.

    The thing is. I need to set an autosuggest for a masive email system, I have a textarea field and the users have to write as maany email adresses as they want.

    rob@gmail.com, rita@hotmail.com, lulu@yahoo.com and so on...

    I allready made the neccesary changes to do the test.php take only the text after "," and then display the match results for it. But I wish to know where do I need to change to not loose my previous results?

    Sorry for my english and Thanks ind advance!

    Posted by: yacatl at June 25, 2007 07:53 PM .

    yacatl said

    Mer said

    I also have another question. I wanted to have multiple options in one text field separated by commas. So every-time after a comma the autosuggest will pop up again. I that possible? Is that something in the JS or the PHP?

    Thanks again


    Hi Mer.

    I'm also looking for that. Is something in both, the PHP and the JS, I allready did the PHP modification and the suggest come up after every comma.

    Still looking for JS section to do this. If I found it I'll tell you.

    Posted by: yacatl at June 26, 2007 12:05 AM .

    yacatl said

    Well, Finally I did it.

    I don't know if it was well done but it works perfect to me.

    What I did is. I set up a text field that does the autosuggest thing. Then, when the user select one I use the callback function to call another js function to fill the textarea field with the actual string comma separate and the new string from the text field.

    Something like that.

    var options_xml = {
    script: function (input) { return "autosuggest/busquedaAJAX.php?input="+input+"&vendedora="; },
    varname:"input",
    highlightfirst:true,
    callback: function (obj) { setTimeout('cargaCorreoAJAX()',1000);}
    };
    var as_xml = new bsn.AutoSuggest('buscador', options_xml);


    Posted by: yacatl at June 26, 2007 02:12 AM .

    Yaya said

    Hi,

    I am French and I use it, but I cannot because it does not accept letters: èéàç

    What must I transform?

    Thx

    Posted by: Yaya at June 26, 2007 08:59 AM .

    bsn said

    @yaya

    make sure your using the same character encoding for everything:
    either utf-8 or iso-5589-1 (latin 1).

    then it should work.

    Posted by: bsn at June 26, 2007 09:09 AM .

    Yaya said

    @bsn : Thank you for your answer

    My homepage contains this :

    I transform your by this:
    /suggestion/js/bsn.AutoSuggest_2.1_comp.js" charset="iso-8859-1">
    /suggestion/css/autosuggest_inquisitor.css" type="text/css" media="screen" charset="iso-8859-1" />

    and
    echo "";
    for ($i=0;$i {
    echo "".$aResults[$i]['value']."";
    }
    echo "";

    but nothing ...
    example for this word : salé => sal�

    thx

    Posted by: Yaya at June 26, 2007 09:44 AM .

    vertygo said

    is there anyway, using the example/demo files as is, for the url to change to whatever is in the $aInfo array ?

    ie. www.test.com has the autosuggest, it's clicked, and the value of $aInfo is www.test.com/foobar so it goes to that page.

    Any help would be greatly appreciated.

    Posted by: vertygo at June 29, 2007 12:23 PM .

    bsn said

    @vertygo

    You don't have to change the .js

    Just write a custom callback function

    callback = function (obj)
    {
       window.location.href = obj.id
    }

    (Assuming that you pass the required url as the "id" field...)


    Tim.

    Posted by: bsn at June 29, 2007 12:31 PM .

    Serge said

    Hi BSN,

    As some people have already mentioned, when you use both prototype FW and BSN autocomplete, then "_bsn.Ajax is not a constructor" error appears.

    Any suggestions?
    Thx.

    Posted by: Serge at June 29, 2007 04:44 PM .

    bsn said

    Hi Serge,

    I've answered your question before - it's just difficult to find the answer in the comments...

    I've added a section about how to avoid prototype conflicts to the original post above.

    Tim.

    Posted by: bsn at June 29, 2007 04:58 PM .

    Serge said

    Hi BSN and other interested!

    Having tried some things, i came to an easy but questionable solution to constructor problem.

    I renamed _bsn.Ajax in bsn_autocomplete.js file to _bsn.Ajax2 and everything worked ever since.

    Have fun!
    And BTW, your autocomplete rules! ;)

    Posted by: Serge at June 29, 2007 04:59 PM .

    vertygo said

    @bsn

    sorry, where would I put that callback function ?

    Posted by: vertygo at June 29, 2007 07:35 PM .

    Carlos said

    Very nice tool...

    I tested it and find that function getSuggestions do a doAjaxRequest when it's not necessary.

    This is a fix:

    _bsn.AutoSuggest.prototype.getSuggestions = function (val)
    {

    // if input stays the same, do nothing
    //
    if (val == this.sInput)
    return false;

    // input length is less than the min required to trigger a request
    // reset input string
    // do nothing
    //
    if (val.length {
    this.sInput = "";
    return false;
    }


    // if caching enabled, and user is typing (ie. length of input is increasing)
    // filter results out of aSuggestions from last request
    //
    if (val.length>=this.nInputCharsLastQuery && this.aSuggestions.length && this.oP.cache
    && val.substr(0,this.sInputLastQuery.length).toLowerCase() == this.sInputLastQuery.toLowerCase() /* csz */
    )
    {
    var arr = [];
    for (var i=0;i {
    /* csz
    if (this.aSuggestions[i].value.substr(0,val.length).toLowerCase() == val.toLowerCase())
    arr.push( this.aSuggestions[i] );
    */
    if ( this.aSuggestions[i].value.toLowerCase().indexOf(val.toLowerCase()) != -1 ) {
    arr.push( this.aSuggestions[i] );
    }
    }

    this.sInput = val;
    this.nInputChars = val.length;
    //this.aSuggestions = arr; csz

    this.createList(arr); //this.aSuggestions); csz

    return false;
    }
    else
    // do new request
    //
    {
    this.sInput = val;
    this.nInputChars = val.length;
    this.sInputLastQuery = val;
    this.nInputCharsLastQuery = val.length;

    var pointer = this;
    clearTimeout(this.ajID);
    this.ajID = setTimeout( function() { pointer.doAjaxRequest() }, this.oP.delay );
    }

    return false;
    }


    Thanks,

    csz

    Posted by: Carlos at July 4, 2007 09:32 PM .

    Carlos said

    I make a mistake, this is the code:

    
    

    _bsn.AutoSuggest.prototype.getSuggestions = function (val)
    {

    // if input stays the same, do nothing
    //
    if (val == this.sInput)
    return false;

    // input length is less than the min required to trigger a request
    // reset input string
    // do nothing
    //
    if (val.length {
    this.sInput = "";
    return false;
    }


    // if caching enabled, and user is typing (ie. length of input is increasing)
    // filter results out of aSuggestions from last request
    //
    if (val.length>=this.nInputCharsLastQuery && ( this.aSuggestions.length || this.aSuggestionsLastQuery != null ) && this.oP.cache
    && val.substr(0,this.sInputLastQuery.length).toLowerCase() == this.sInputLastQuery.toLowerCase() /* csz */
    )
    {
    if ( this.aSuggestionsLastQuery == null ) {
    this.aSuggestionsLastQuery = this.aSuggestions;
    }
    var arr = [];
    for (var i=0;i {
    if ( this.aSuggestionsLastQuery[i].value.toLowerCase().indexOf(val.toLowerCase()) != -1 ) {
    arr.push( this.aSuggestionsLastQuery[i] );
    }
    }

    this.sInput = val;
    this.nInputChars = val.length;
    this.aSuggestions = arr;

    this.createList(arr); //this.aSuggestions); csz

    return false;
    }
    else
    // do new request
    //
    {

    this.sInput = val;
    this.nInputChars = val.length;
    this.sInputLastQuery = val; // csz
    this.nInputCharsLastQuery = val.length; // csz
    this.aSuggestionsLastQuery = null; // csz

    var pointer = this;
    clearTimeout(this.ajID);
    this.ajID = setTimeout( function() { pointer.doAjaxRequest(); }, this.oP.delay );

    }

    return false;
    }

    Thx.
    csz

    Posted by: Carlos at July 4, 2007 11:07 PM .

    Sébastien Allard said

    In doAjaxRequest(), there is a bug when the field value is placed in the URI.

    Currently the value is being escaped with escape() rather then encoded with encodeURIComponent(). This makes a huge difference with diacritics because they won't get encoded properly. encodeURI() should not be used either since it won't escape characters such as "&?/" that needs to be escaped.

    The correction should be:

    _bsn.AutoSuggest.prototype.doAjaxRequest = function ()
    {
    var pointer = this;

    // create ajax request
    //
    if (typeof(this.oP.script) == "function")
    var url = this.oP.script(encodeURIComponent(this.fld.value));
    else
    var url = this.oP.script+this.oP.varname+"="+encodeURIComponent(this.fld.value);

    if (!url)
    return false;

    var meth = this.oP.meth;

    var onSuccessFunc = function (req) { pointer.setSuggestions(req) };
    var onErrorFunc = function (status) { alert("AJAX error: "+status); };

    var myAjax = new _bsn.Ajax();
    myAjax.makeRequest( url, meth, onSuccessFunc, onErrorFunc );
    }

    Posted by: Sébastien Allard at July 6, 2007 08:58 PM .

    Steve said

    Any luck on getting it to automatically submit when you select a result?

    Posted by: Steve at July 7, 2007 01:19 AM .

    Steve said

    Also, I am having validating issues with it...

    Posted by: Steve at July 7, 2007 01:20 AM .

    Steve said

    We have this working but when we try it in a subdomain with an absolute URL for the js file, it does not work. Any suggestions?

    Posted by: Steve at July 7, 2007 05:28 PM .

    Peter said

    I use the script within other 's and it seems when one scrolls, the autosuggest-box appears relative to the page and not the .

    I had to remove the body {position: relative;} in order to make it work with my own CSS.

    Any suggestions?

    Posted by: Peter at July 8, 2007 02:27 AM .

    Peter said

    hmm > and < was sorted away... Try again:

    I use the script within other div's and it seems when one div scrolls, the autosuggest-box appears relative to the page and not the div.

    I had to remove the body {position: relative;} in order to make it work with my own CSS.

    Any suggestions?

    Posted by: Peter at July 8, 2007 02:30 AM .

    bsn said

    @Peter

    In the createList function the pulldown is set absolute positioned relative to the body element. If you are scrolling your div independently from the body element, that's why the pulldow stays still (relative to the body).

    How to get around this:
    - Set the position of the autosuggest field container element to 'relative'
    - Rewrite the positioning code to set the position of the field relative to it's parent, not to the body
    - Rewrite the script to append the pulldown in the parent element of the field (possibly giving it a high z-index)

    Tim.

    Posted by: bsn at July 9, 2007 09:13 AM .

    hardyke said

    Hi,

    Thx for this great piece of code but apparently I'm missing something.
    I've implemented your demo piece and I retrieve the dropdown list with the users.
    But when I submit the page the script is not passing the GET variable.
    I receive this as a result http://ip/testajax/? and no variables are passed when I do a vardump of the get array.
    What am I doing wrong?

    Posted by: hardyke at July 9, 2007 04:42 PM .

    Dave said

    Has anyone figured this out yet? I need to know how to do it.

    Thanks!
    Dave

    Matthew said

    Wonderful script - looking to customise for my particular site.

    The script is looking up street names from a DB. Many of the street names are made up of more than one word. eg TRIQ ABBE R. A. DE VERTOT

    This makes matching the first character not very useful.

    I have my array populated using LIKE %'.$input.'% which populates the main array properly with the street names based on any part string matching.

    However, the rest of your script seems to loose these records and only display those matching the first letter onwards.

    Any ideas which functions I need to look at to resolve this? if at all possible.

    Thanks! Matthew


    Posted by: Dave at July 10, 2007 04:55 AM .

    Jav said

    Hey guys

    this script is phenomenal and easy to implement, just be a little patient and be meticoulous.

    Here are a list of problems I had and I hope people will learn from my mistakes:

    1) Link to the .css file properly (i feel so dumb)
    2) I used the JSON version, so make sure the mime-headers are correct for the script that is actually creating the contents of the autosuggest box.

    Other than that it worked fine after about 2 hours of work

    Posted by: Jav at July 10, 2007 11:19 AM .

    Frank said

    Tim,

    Thanks for this great script! I'm an intermediate coder but am new to AJAX and wondering if you can help me out. I'm trying to adapt your autosuggest functionality to work in a non-ajax style. Let me explain...

    I've implemented your autosuggest functionality to a Lotus/Domino form in which I have approx. 50 fields which will be using the same dataset. They're ingredient fields for a recipe application. I'm preloading the dataset (over 2000) very quickly when the form is first opened into a hidden field (shown below, but can easily put into a JS array if need be). I figure it's more efficient to load the list once that have the server get called every time each of the 50 fields are modified.

    Basically I'm looking for a way to have the autosuggest functionality pull from this hidden field or JS array instead of performing a call to the server. Keeping the code client-side will be faster in this instance. Also the dataset is a dynamic combination of two independent datasets, updated frequently, which makes performing a single server call impractical.

    Any guidance or suggestions would be greatly appreciated!

    Posted by: Frank at July 10, 2007 04:57 PM .

    Problems? said

    Hi BSN,

    thanks for the great script. Has anyone noticed an issue when the drop down covers other form elements? I have a page that has various Text boxes as input, in addition to a select box. The Auto Suggest drop down is (when in use) covers the select box, but the select box is visable over the Auto Suggest drop down, also it is selectable. Does anyone have any idea why this would happen or how it can be fixed?

    Also does anyone have a working example of a form (and backend processing script in PHP,Perl or ASP) of Auto Suggest being used by multiple fields, or against multiple database tables.

    Thanks in advance,

    Samual

    Posted by: Problems? at July 11, 2007 09:37 AM .

    Problems? said

    Hi BSN,

    thanks for the great script. Has anyone noticed an issue when the drop down covers other form elements? I have a page that has various Text boxes as input, in addition to a select box. The Auto Suggest drop down is (when in use) covers the select box, but the select box is visable over the Auto Suggest drop down, also it is selectable. Does anyone have any idea why this would happen or how it can be fixed?

    Also does anyone have a working example of a form (and backend processing script in PHP,Perl or ASP) of Auto Suggest being used by multiple fields, or against multiple database tables.

    Thanks in advance,

    Samual

    Posted by: Problems? at July 11, 2007 09:38 AM .

    Chase Peeler said

    Great script, all the functionality of other auto completes out there but much much simpler. Only one thing, is there a way I can turn off the fade effect? I want the suggest box to go directly from visible to invisible.

    Thanks in advance

    Posted by: Chase Peeler at July 11, 2007 11:44 PM .

    Ian said

    I have incorporated the autosuggest in the local development version of my software and it works fine. When I upload everything to the server it gives an AJAX error 404. This seems to imply that it cannot find the php bit to do the search of names but it is there.
    Any idea what this might be, I've spent the best part of a day trying to get it to work.

    I have also the same issue as someone else about select boxes showing but you can get round that by putting in some code to make them hidden when the list xcomes up and unhide them again when the list goes away.

    Put something like
    if (document.forms[0].name == 'diary'){
    diary.diary_method.style.visibility = "hidden";
    }
    in the bsn.AutoSuggest.prototype.getSuggestions function and the opposite
    if (document.forms[0].name == 'diary'){
    diary.diary_method.style.visibility = "visible";
    }
    in the _bsn.AutoSuggest.prototype.clearSuggestions function

    This seems to work OK.

    Thanks

    Posted by: Ian at July 12, 2007 03:53 PM .

    Steve said

    Hi Tim,

    Great script, I hope to see further work on it since it's such a great resource.

    Anyway, I'd like to report a minor bug with the code in V 2.1.2. In the non-compressed version, line 548 will error when:
    1) The target field contains the minimum number of characters for AS to pay attention to it, and
    2) The Enter key is pressed without the AS window coming up and without something being highlighted. This will occur if you let the popup time out, or if you've already selected a value with Enter, and you just press Enter again.

    This error occurs on the line within the function:

    _b.AutoSuggest.prototype.setHighlightedValue = function ()

    The code reads:

    this.sInp = this.fld.value = this.aSug[ this.iHigh-1 ].value;

    The javascript error returned is:

    this.aSug[this.iHigh - 1] has no properties

    Line 548

    Hope that helps,

    Steve

    Posted by: Steve at July 12, 2007 11:51 PM .

    Henning said

    @Yaya

    I know what you mean, I have the same problems with Æ, Ø and Å here in Norway.

    To get it too work with xml and encoding you must save your result as an XML-file, you can not just get it from the PHP or other script.

    That's not an option for me so I'm looking at "json" at the moment. i don't get js-errors any more, but "AutoSuggest" only returns a questionmark when typing Æ, Ø or Å in the input field.

    BTW, great coding here BSN

    Henning

    Posted by: Henning at July 13, 2007 12:09 AM .

    Yaya said

    Hi,
    on my website www.produits-bretons.fr , I put your code ( utf-8), however accents (àèé Latin) doesn'tt work.

    If somebody find the solution I would be happy, otherwise I cannot put this code :-(

    thx

    Posted by: Yaya at July 13, 2007 04:31 PM .

    fernando said

    Great script!
    When have a select field down the popup, the select field hide the suggest!!

    how can I fix this problem?

    Posted by: fernando at July 15, 2007 07:18 PM .

    Spiros S. said

    Greetngs,

    Thats a great script, thank you! However I have encoutered a problem when using it with IE6. When you have a form element (text field, drop menu etc) below the selections that the script generates, the field actaully appears above the script (meanig the selections menu generated by the script fails to cover the form element). I have tried playing with z-indexes but that does not help. Any ideas?

    Posted by: Spiros S. at July 16, 2007 12:12 PM .

    Henning said

    selectbox in HTML is always on top, nothing to do about it :-(
    Same for all javascripts

    Posted by: Henning at July 16, 2007 10:13 PM .

    Sébastien Allard said

    Yaya said


    on my website www.produits-bretons.fr , I put your code ( utf-8), however accents (àèé Latin) doesn'tt work.


    v2.1.2 works great with accents. In the previous version, characters where being escaped rather then encoded. This would cause problems depending on the system.

    Make sure you specify the encoding on the pages where you use autosuggest (xml header with an utf-8 encoding, meta/content/charset utf-8 declaration.) The HTTP request from the client will use the encoding of its source. If your page is set to ISO8859 for example, and you are expecting UTF-8 encoding at the server, you won't get the accents.

    Are you on PHP? .NET? Java?

    Posted by: Sébastien Allard at July 16, 2007 10:15 PM .

    Sandhya said

    Hi,

    I am unable to make the autosuggest solution work for my page. Can we have a chat so as to figure out the problem. Please let me know.

    Thanks and Regards,
    Sandhya

    Posted by: Sandhya at July 17, 2007 02:51 AM .

    Alex said

    Hi Tim,

    thanks for this great piece of work. I have a little problem though: The list appears only after every 2nd letter. E.g. I type "B", and the list with results starting with "B" appears, then I add "e" and get "no results", after adding "r" the list (now with "Ber") appears again. If I hit the 2nd key while the list is visible, the list disappears.
    If I type "Be" quickly enough, the result appears, but after the next letter there are "no results" again.
    I use Firefox 2.0.0.5
    What can I do?

    Thanks in advance
    Alex

    Posted by: Alex at July 19, 2007 12:42 PM .

    bsn said

    Hi Alex,

    I know what the problem is, and I'm thinking about it...

    Tim.

    Posted by: bsn at July 19, 2007 01:04 PM .

    Alex said

    Hi Tim,

    same on IE 7.0
    Strangely enough, it works on your demo site with both FF and IE. Can't find a difference.

    Best regards
    Alex

    Posted by: Alex at July 19, 2007 01:26 PM .

    bsn said

    Hi Alex,

    thanks for the heads up - nothing to do with Firefox.

    Get the new version (2.1.3.)

    You have to tell the script the max. number of results it's going to get (your MySQL LIMIT clause). e.g. 25

    The problem is:

    - you type "B", and get ten (LIMITed) results starting with "Ba..." from the DB.
    - you type "e"
    - the script looks in it's cache, but only has results with "Ba" - therefore no results
    - you type "r"
    - the script has no results, and no cache, so it queries the server, and gets the correct results

    New version:

    - set the maxentries setting to 10
    - if the cache has 10 entries, the script ignores it and queries the server in case there are more matches that aren't being shown in the list.

    Posted by: bsn at July 19, 2007 01:34 PM .

    Alex said

    Thanks for this quick response.
    There are still problems though:
    - if *maxentries* set to 10 with "options" var, the following happens:
    1. After the first letter, eg. "B", the list has 23 entries (more than 10). List is shown - OK
    2. After the second letter, "e", the list has 13 entries (more than 10). List is shown - OK
    3. After "r", list has 8 entries (1st time less than 10). List is shown - OK
    4. After "k", list should have 5 entries (2nd time less than 10). List is NOT SHOWN - ERROR

    I tried this with *maxentries = 15*, similar result (list not shown after 1st time less than 15 entries).
    So it seems that, by the second time the list has less than *maxentries*, the script looks in its cache and finds nothing.
    I hope you can fix that.

    Best regards
    Alex

    Posted by: Alex at July 19, 2007 02:12 PM .

    Alex said

    PS: *cache: false* fixes that (no surprise).

    Posted by: Alex at July 19, 2007 02:14 PM .

    Alex said

    Hi Tim,

    I've setup a testpage, where you can see the difference.
    Visit http://sandkarte.de/suggest_test.php
    There are two autosuggest-entryfields for cities, the only difference is the value of cache. In autosuggest-options maxentries is set to 10, as well as MYSQL LIMIT.
    Try typing something like "Berlin", "Frankfurt" or "Dortmund" to see what happens.
    The second row shows some beachsites, try typing "beach" to get a long list. Here maxentries and MYSQL LIMIT is 15.
    See what happens if you type "beach j" on the left and on the right hand side: after " " (whitespace) the list length is under 15 for the first time. While typing "j" on the left hand side shows the correct result ("beach jena"), the list on the right hand side is empty.
    Can't find a solution other than switching "cache" to false.

    And another strange thing: typing e.g. "beag" (no results) throws a JS exception.

    Best regards
    Alex

    Posted by: Alex at July 20, 2007 02:11 PM .

    Costin said

    Hey,
    Cool component and rather lightweight too.
    Suggestion:
    Consider changing the line

    var small = _b.DOM.cE("small", {}, arr[i].info);

    to

    var small = _b.DOM.cE("small", {}, arr[i].info, true);

    or adding an HTML info argument. Maybe folks will need multiline info (like I did :P)

    Posted by: Costin at July 20, 2007 11:42 PM .

    Ariel said

    Hi !, U did a great job with this script !. Now i need to avoid the fade effect. How can i do that ?. Tnx. Good luck !

    Posted by: Ariel at July 21, 2007 03:36 PM .

    Basti said

    Hi bsn,

    Your script is working great (BIG THX!), except one thing i could not manage to get to work:

    The callback function is not working properly. But I dont know where the problem is. When I click the entry everything is fine, but when I press enter it does not follow the link it is supposed.

    Error: obj has no properties
    Source File: www.careshop.de/test.php
    (lower search form)

    I also tried id instead of href....same error.

    There you can try the script too.

    var options_xml = {
    script:"Autosuggest.php?",
    minchars: 1,
    timeout: 6000,
    delay: 500,
    shownoresults: true,
    noresults:"Versuchen Sie die Erweiterte Suche",
    cache: false,
    varname:"search",
    callback: function(obj){window.location.href = obj.href},
    whereSubmit:"quick_find"
    };
    var as_xml = new bsn.AutoSuggest('search_xml', options_xml);

    Can somebody help me pls?

    Basti

    Posted by: Basti at July 21, 2007 05:43 PM .

    Basti said

    I think I got it!!!! I made a mistake in the js. THX for the great script!!!

    Posted by: Basti at July 23, 2007 11:15 AM .

    bsn said

    @anyone who doesn't want the fade effect

    To kill the fade, change clearSuggestions to:

    _b.AutoSuggest.prototype.clearSuggestions = function ()
    {
      this.killTimeout();
      _b.DOM.remE(this.idAs);
    };
    

    Tim.

    Posted by: bsn at July 23, 2007 11:55 AM .

    upstatecoder said

    GREAT SCRIPT! Need some help though :(

    I'm having trouble getting results. Everything is implemented exactly as requested but nothing is being returned. Here are my scripts:

    XML
    http://www.buzzsocket.com/assets/ajax/autosuggestvenue.asp?search=test
    *see how it returns two venues

    PAGE
    http://www.buzzsocket.com/assets/iframe/venues/

    My text field ID is "search". Here is the javascript on the bottom of my page:

    var options = {
    script: "../../ajax/autosuggestvenue.asp?",
    varname: "search",
    json: true
    };
    var as = new AutoSuggest('search', options);


    Any thoughts? Your help is GREATLY appreciated! (btw - your site is awesome!)

    Posted by: upstatecoder at July 23, 2007 06:39 PM .

    bsn said

    @upstatecoder

    try adding an xml declaration to your response, e.g.:

    <?xml version="1.0" encoding="utf-8" ?>

    Posted by: bsn at July 23, 2007 07:05 PM .

    upstatecoder said

    Thanks! I actually figured out what was going on - JSON was set to true. All I did was set to False and it worked as I was pulling XML.

    Thanks for the prompt response!

    Posted by: upstatecoder at July 23, 2007 11:28 PM .

    Javier said

    Works great for IE7 and firefox

    on IE6 the box holding the autosuggest timesout really fast (like 0.25s). I change the timeout option to 10000 (10s) and the box fires after 10s for 0.25s.

    Any suggestions?

    Posted by: Javier at July 24, 2007 01:01 PM .

    Shannon said

    Alright, like most this is useless unless using it on a database. I am trying to query a MySQL database to populate the suggestions list:

    require('get_connected.php'); //Connect to the database
    $sql=mysql_query("SELECT first_name FROM canada WHERE first_name LIKE('%" .$_GET['input']. "%') ORDER BY first_name");
    $aUsers = mysql_fetch_array($sql);

    2 PROBLEMS I NEED HELP ON
    First One: let's say I have Sang, Shannon and Sirin in the field first_name.

    If I type in "S" in the suggestion box it displays Sang... but does not list all the "S" names. Only the first one. I tried a for loop and a while loop with no luck.

    Second One: Now let's say I type in "Si", a "No Results" is displayed... but if I type Sir it shows Sirin. What's up with that?

    Thanks for any help or suggestions.

    SC

    Posted by: Shannon at July 24, 2007 11:10 PM .

    Shannon said

    Okay, I figured it out. A real easy MySQL query... All I needed to do was search for a users first name, this is how I did it in the JSON search (should get you to the XML if you desire it).

    All code should go in the test.php file:


    STEP 1.
    //Place this code above the $aUsers = array(
    require('database.php'); // include database
    if ($result = mysql_query("SELECT distinct(column) FROM table WHERE column LIKE('" .$_GET['input']. "%') ORDER BY column")) {
    if (mysql_num_rows($result)) {
    while ($row = mysql_fetch_assoc($result)) {
    $aUsers[] = $row['column'];
    }
    }
    }

    STEP 2. Comment out the $aUsers array by using /* and */

    STEP 3. Replace the table and column name to your specific MySQL configuration.


    This code replaces the current $aUsers variable with a mysql query.

    Hope that works. If it does, give me a shout out. If it doesn't contact me and maybe I can help.


    Posted by: Shannon at July 25, 2007 02:00 AM .

    Shannon said

    Okay, I tried to this in three places. On WAMP (my local host) and two different servers. Works great on localhost and on one server, but doesn't work on another server. All of which are running PHP 5. Any ideas?

    Thanks

    Posted by: Shannon at July 25, 2007 07:49 PM .

    Eric JK said

    I'd like to suggest something:

    In programming means, I'd like it to keep visible until the user press ESC or ENTER or click outside...

    thanks

    Posted by: Eric JK at July 26, 2007 12:37 AM .

    Kit Grose said

    There are two bugs I can see (running Safari 2.0.4 on OS X Tiger):

    1. If I type 'Sm', I get results for Smith and Smothers. If I type an extra 'i' (extending the query to 'Smi'), I get 'Smith'. The issue is when I backspace that 'i' (returning to 'Sm') and then reasonably quickly type an 'o' (leaving me with 'Smo'), I get "No Results!". If I delete the 'o', and then type it again, I get Smothers showing up.

    2. The arrow keys navigate me up/down TWO results at a time. When I would have gone past the end, it reverts me back to the bottom option (so if I have the options A, B, C, D, E, and then I click down, option B is selected. Pressing down again selects D. Pressing down again selects E. Pressing up then selects C, and up again selects A). The options are all navigable with the mouse, though

    Posted by: Kit Grose at July 27, 2007 05:26 AM .

    bigEar said

    I have simply downloaded the code into a local directory.
    I use ie7 to view bsn.AutoSuggest_2.1.3

    After receiving and oking an active X warning,

    everything looks good.

    I then add text to the text field but nothing happens?

    I am not using my code at all only the scripts provided.

    What am I doing wrong?

    Posted by: bigEar at July 29, 2007 07:31 PM .

    fpmWEB said

    Hi.

    Problems with select list ()
    I have an input text with autosuggest and a select list.

    The autosuggest div's allways they always are underneath.
    some solution? some patch?

    Thanks !

    Posted by: fpmWEB at July 30, 2007 11:15 AM .

    Kevin said

    Hello,

    I am writing an app for the iPhone, and would LOVE to use this scrip in my app. I have gotten this script to work on my reuglar web pages, but it doesnt work on the iPhone's safari browser.

    Any ideas? I would really appreciate any help!

    Thanks,
    Kevin

    Posted by: Kevin at July 30, 2007 05:33 PM .

    Kevin said

    Hello,

    I am trying to get this script to work on the iPhone for my new web app. It doesn't seem to ever fire. I have the script working otherwise (on Firefox and IE), but it wont work on the iPhone.

    Any ideas? I would really appreciate any help on this issue!

    Posted by: Kevin at July 30, 2007 05:35 PM .

    Kevin said

    Hello,

    I am trying to get this script to work on the iPhone for my new web app. It doesn't seem to ever fire. I have the script working otherwise (on Firefox and IE), but it wont work on the iPhone.

    Any ideas? I would really appreciate any help on this issue!

    Posted by: Kevin at July 30, 2007 05:37 PM .

    Sarah said

    Is there a way that I can make it display all results if the person does not type anything in, or if they delete what they typed in? I have a small list of options (about 50). I would like to use this to display all by default, and narrow down the number of options if they decide to type something in. If they then delete what they typed, I would like it to show all again. So this would work like a filter on my results.

    It will be displayed as a list of links on the page, not attached to the textbox.

    Thanks.

    Posted by: Sarah at July 30, 2007 06:36 PM .

    Matt M said

    Hey man,

    I'm trying to implement the auto suggest into a test document just to see if it will work for me. Is there a way for the data to come from an xml file instead of a php file? And can this be tested locally instead of remotely?

    thanks

    Posted by: Matt M at August 1, 2007 09:53 PM .

    ScubaSteve said

    First, thank you for this great script. I struggled a bit with the "back end" part (test.php), having no prior JSON experience, but now I have it working.

    Also, a bug: I'm still exhibiting the "no results!" every other letter typed bug, even though I'm using 2.1.3, which claims to have fixed that. Is anyone else still seeing this? And is there a fix in sight?

    Thank you!

    Posted by: ScubaSteve at August 2, 2007 01:18 AM .

    ScubaSteve said

    Just a follow-up to the above post, by adding:

    cache:false,

    to the "var options" section, the bug goes away, so I guess the bug has something to do with the caching as Alex mentions.

    Posted by: ScubaSteve at August 2, 2007 01:29 AM .

    ScubaSteve said

    Yet another follow-up.

    By using "cache:false," I don't get the "No results!" every other letter bug, but I also never get the "No results!" to pop up at all (and yes, I do have "shownoresults:true,".

    This means one has to pick between showing "No results!" erroniously or not displaying it at all.

    Thanks for trying to fix!

    Posted by: ScubaSteve at August 2, 2007 01:43 AM .

    bsn said

    Hi everyone.

    There is a caching bug, so set cache to false. I've got so much work on at the moment that I haven't had a chance to look at it. Will post a fix when I get around to it!

    SORRY!

    Tim.

    Posted by: bsn at August 2, 2007 09:13 AM .

    ScubaSteve said

    No worries, Tim! Thanks for the update!

    Posted by: ScubaSteve at August 2, 2007 05:34 PM .

    Kavehmb said

    Hi, I have a problem with using script as a function.
    The code doesn't pass my "input" value to the php script!

    script:function ()
    {
    return "ajax/21/codingAuto.php?json=true&limit=10&nahve="+document.getElementById('f1_p').value+"&"
    }

    OR

    script:function (input)
    {
    return "ajax/21/codingAuto.php?json=true&limit=10&nahve="+document.getElementById('f1_p').value+"&"
    }

    Posted by: Kavehmb at August 4, 2007 06:15 AM .

    Carlo said

    Is it possible to have auto suggestions for parts of values? For instance in the demo, if I would type in "Dodie" that "Whishaw, Dodie" would come up as a suggestion?

    Posted by: Carlo at August 7, 2007 12:05 PM .

    Evilz said

    Hello,

    I hope my question doesn't have an answer already ...

    Can I use you control without post back.

    I want to load data in the first call. Using a other js for example what create the JSON object onload.

    Is that possible ?

    Posted by: Evilz at August 7, 2007 03:44 PM .

    Blake said

    If people are still having the IE6 issue where the suggestion list stays on screen after an item has been selected or the search box has been cleared I have made a quick and dirty fix for the problem. Just replace these functions with the code show.

    ***This assumes you are running the prototype library****

    If Not Change the "$("as_"+this.fld.id).remove();"
    lines to a DOM equivalent method for removing an element from the page.

    ******************************************************

    _bsn.AutoSuggest.prototype.onKeyPress = function(ev)
    {

    var key = (window.event) ? window.event.keyCode : ev.keyCode;

    // set responses to keydown events in the field
    // this allows the user to use the arrow keys to scroll through the results
    // ESCAPE clears the list
    // TAB sets the current highlighted value
    //
    var RETURN = 13;
    var TAB = 9;
    var ESC = 27;

    var bubble = true;

    switch(key)
    {

    case RETURN:
    this.setHighlightedValue();
    bubble = false;
    $("as_"+this.fld.id).remove();
    break;


    case ESC:
    this.clearSuggestions();
    $("as_"+this.fld.id).remove();
    break;
    }

    return bubble;
    }

    _bsn.AutoSuggest.prototype.onKeyUp = function(ev)
    {
    var key = (window.event) ? window.event.keyCode : ev.keyCode;


    // set responses to keydown events in the field
    // this allows the user to use the arrow keys to scroll through the results
    // ESCAPE clears the list
    // TAB sets the current highlighted value
    //

    var ARRUP = 38;
    var ARRDN = 40;

    var bubble = true;

    switch(key)
    {


    case ARRUP:
    this.changeHighlight(key);
    bubble = false;
    break;


    case ARRDN:
    this.changeHighlight(key);
    bubble = false;
    break;


    default:
    if (this.fld.value == ''){
    $("as_"+this.fld.id).remove();
    }else{
    this.getSuggestions(this.fld.value);
    }
    }

    return bubble;

    }

    I hope this helps!

    Blake

    Posted by: Blake at August 8, 2007 05:17 PM .

    Rauan Maemirov said

    Hi, all!

    I want to ask if it possible to make multiply suggestion, like in Blogger.

    I mean, e.g. I'm typing some part of word, then click on suggestion. Then i'm typing ','(comma) and doing it once again and autocomplete suggests me smth again.

    Posted by: Rauan Maemirov at August 8, 2007 06:27 PM .

    Decbrad said

    Hi there, the script looks absolutely fantastic, but I can't get it to work? New to AJAX/JavaScript. Is there a detailed setup / readme file online that I have missed?

    regards and thanks again!
    Decbrad

    Posted by: Decbrad at August 9, 2007 12:03 AM .

    Kelby said

    Hi, set up the script using a mysql db as the source, and an asp page creating xml from the query.

    However once I have selected an item from the options. and press submit, none of the values are passed via the url.

    try it out:
    http://gigglechops.com/find.htm

    Posted by: Kelby at August 13, 2007 01:17 AM .

    alex said

    Carlo said

    > Is it possible to have auto suggestions for parts of values? For instance in the demo, if I would type in "Dodie" that "Whishaw, Dodie" would come up as a suggestion?

    Carlo, just change your SQL Statement! Type "LIKE '%[search]%'" (instead of '[search]%') in the WHERE clause.

    Posted by: alex at August 15, 2007 09:37 AM .

    Alex said

    Kelby,
    the input-field has no name, so no variable to put the selected town into.

    Posted by: Alex at August 15, 2007 09:40 AM .

    nick said

    whenever i arrow down to a suggestion and hit the 'enter' key, the form submits, but i have a seperate submit button i want the user to press to submit the form. any way i can prevent it from automatically submitting? this doesn't happen when i use the mouse button to click a result.

    thanks!

    Posted by: nick at August 15, 2007 05:52 PM .

    Kelby said

    Thanks Alex for the pointer on the name value.. I knew I was missing something obvious.

    Next question, which also probably has an obvious answer..

    I need to pass the value of the id field through as well when the submit button is pressed. Any ideas how that is done?

    Posted by: Kelby at August 16, 2007 02:14 AM .

    Ash said

    Great Script!!!

    I use the callback function to populate an additional field with the "info" value as described by BSN. (Thanks for everything Tim!) I am wondering if it is possible to populate more fields of my form in a similar fashion.

    For example, I have an order form that takes customer info and order details. I use the script to see if a customer is already in the database. If so, I would like his information to be auto entered into the appropriate fields.

    I tried a few things like making the info value an array, but I could not get it to work. (I couldn't figure out how to refer to the individual values in the callback. They kept returning as undefined.) I am way over my head with this. Can anyone help me? Is this possible?

    Posted by: Ash at August 16, 2007 08:32 AM .

    Ron said

    Has anyone else encountered issues when the user types in something so fast that they have already tabbed out of the field before the autosuggest has time to appear?

    I didn't find any comments on this, so I'm assuming no one has posted about it.

    I also did not find a simple property on the input element that tells you if it has focus. So here is the code I used to work around this issue:


    In the "init variables" area, add this line:
    this.hasFocus = false;

    Right below where onkyeup and onkeydown (around line 89) are attached to the element, add these lines:

    this.fld.onfocus = function(ev){ return p.onFocus(ev); };
    this.fld.onblur = function(ev){ return p.onBlur(ev); };


    Then add these functions below somewhere:


    _b.AutoSuggest.prototype.onFocus = function(ev)
    {
    this.hasFocus=true;
    }

    _b.AutoSuggest.prototype.onBlur = function(ev)
    {
    this.hasFocus=false;
    }

    Then add this line to the beginning of the createList function:

    if(!this.hasFocus) return;

    Posted by: Ron at August 17, 2007 06:49 PM .

    Kelby said

    Tried lots of things, still not getting the id field of the xml passed through the submit url.

    any ideas?

    Posted by: Kelby at August 18, 2007 11:02 PM .

    Posted by: Kelby at August 18, 2007 11:11 PM .

    Ash said

    @ Kelby

    I am not too good with this ajax stuff yet, but try this...

    In the script at the end of your page, put the callback within the "var options_xml":

    var options_xml = {
    script: function (input) { return "towns.asp?input="+input+"&testid="+document.getElementById('testid').value; },
    callback: function (obj) { document.getElementById('testid').value = obj.id; },
    varname:"input"
    };

    In fact, if you aren't using JSON, you can get rid of the "var options" and "var as_json" parts and put all your settings in the "var options_xml".

    Let me know if that does not work.

    Posted by: Ash at August 19, 2007 12:21 AM .

    Kelby said

    Cheers Ash, that works much better now. one last question,

    How would I collect an extra piece of info,

    eg the xml provides the id number, town name and county from the db

    I want to add postal area in as well so that can be passed through with the submit url as well.

    Posted by: Kelby at August 19, 2007 01:46 AM .

    Ash said

    Kelby,

    I have only been able to work with up to three pieces of data. One using "id", one using "value", and one using "info". I assume that is how you are passing your id, town, and county. If so, I am having the same problem as you. I have experimented with the "info" attribute and also setting my own attributes in order to get more data in there somehow. But I have had no luck. (See my post above.)

    Can anyone help us with this?

    A possible solution for you, since you are submitting the data, is to query the database again after the submission. Then you could pass as much data as you want. If I am understanding what you want to do...

    Posted by: Ash at August 19, 2007 03:20 AM .

    Zurita said

    Hola,

    Estoy tratando de configurar autoSuggest con mysql pero no he tenido suerte, alguien seria tan amable de enviarme a mi mail un ejemplo o ponerlo en un post

    Saludos

    Posted by: Zurita at August 19, 2007 07:25 AM .

    Zurita said

    Sorru my email es czurita gmail.com

    Cya

    Posted by: Zurita at August 19, 2007 07:26 AM .

    Stephane said

    Congratulations for your work!
    I was looking for a clean way to do it and your is very subtle, especially especially the DOM part.
    I can also use DWR with, which is nice too.

    Posted by: Stephane at August 21, 2007 02:13 PM .

    Stinger said

    Hi,
    I've been working on this off and on now for two months, and I feel really stupid...

    xSquall very kindly provided a test.php for a simple query to a MySQL database. (Comment 19)

    bsn spotted (Comment 26) that the two lines that read...
    for ($i=0;$i
    should have read...
    for (i=0;i<count($arr);i++)
    (newbie question... should the correction be $i instead of i?)

    So this is what I did...

    1. Cut and pasted xSquall's php into a file called test.php with correct permissions.
    2. Added php tags at the beginning and end
    3. Corrected the two "for ($i=0;$i" entries
    4. Changed parameters in mysql_connect and mysql_select_db
    5. Changed mysql_query to match my database
    6. Changed the while loop to match my database

    Result... nothing.
    The suggestion box doesn't appear
    I've echoed results back from the script, down as far as the while loop, but excluding the REQUEST and that all appears to work.

    I have a very simple MySQL database called sales, with a table called client with two fields id_client, and name_client, which I think is almost identical to the example.

    <?php
    $input = $_REQUEST['input'];
    $link = mysql_connect("localhost", "xxx", "xxx");
    mysql_select_db("sales",$link);
    $qr = mysql_query("SELECT id_client,name_client FROM client WHERE name_client LIKE '".$input."%'",$link);
    while ($row = mysql_fetch_array($qr))
    {
    $aResults[] = array( "id"=>($row['id_client']) ,"value"=>htmlspecialchars($row['name_client']), "info"=>htmlspecialchars($row['name_client']) );
    }

    ====cut====
    Rest as per example with bsn corrections.

    I am very sorry to be posting this MySQL based question.

    Thank you for reading this far
    C.

    Posted by: Stinger at August 22, 2007 06:31 PM .

    john said

    I am having trouble using mysql to pull results from. Can someone please post or send me their test.php file so i can compare it to mine?

    TIA

    Posted by: john at August 26, 2007 07:28 PM .

    Kunjan said

    Hi bsn
    This is a nice script.
    However, I am facing problem with dropdown list background transparency. The results are populated fine in dropdown list but the list is not quite visible as the other form fields, cover the dropdown list. The list does not come in foreground and not quite readable..

    Could you please suggest some way I can make the list opaque so that the other fields do not obstruct the view of the drop down list.

    Posted by: Kunjan at August 28, 2007 04:56 PM .

    John West said

    Hi ben! I have a problem... I am using a pure CSS layout and I have some code:





    var options = {
    script:"iwrp.xml/iwrp.populate.autosuggest.aspx?field=Title&",
    varname:"sInput",
    minchars:1
    };
    var as = new AutoSuggest('ctl00_ctl00_MasterContentBody_ContentPlaceHolder1_txtTitle', options);

    For whatever reason, when I run it... it works fine but the autosuggest list appears at the bottom of the site! I am using the version before this one (matches the layout we use). Do you have any ideas?

    Posted by: John West at August 29, 2007 12:28 AM .

    Alexandre B said

    Very nice script! I made a nice .net wrapper around it to make it easy for us to integrate it into our projects. Basically just a matter of drag and dropping a control on the page and setting properties now :)

    For people having issues with the caching, I made a small fix that you may like. Basically my "service" page returns more results than I need (max at 50) and on the client side in the getSuggestions method I did the following modification :


    var l = this.aSug.length;
    if (this.nInpC > ol && l && l {
    var arr = [];
    for (var i=0;i {
    if(this.aSug[i].value.toLowerCase().indexOf(val.toLowerCase()) > -1)
    arr.push( this.aSug[i] );
    }

    /* added this so that if display array have less than 10 elements but in the client has in cache more than 10
    elements then we re-query the server to obtain a new set of cache.*/
    if(l > 10 && arr.length {
    var pointer = this;
    var input = this.sInp;
    clearTimeout(this.ajID);
    this.ajID = setTimeout( function() { pointer.doAjaxRequest(input) }, this.oP.delay );
    }
    else
    {
    this.aSug = arr;
    this.createList(this.aSug);
    return false;
    }
    }
    else
    // do new request
    //
    {
    var pointer = this;
    var input = this.sInp;
    clearTimeout(this.ajID);
    this.ajID = setTimeout( function() { pointer.doAjaxRequest(input) }, this.oP.delay );
    }


    MaxEntries is now 51. What this does is this : when the client has in cache more than 10 results, but filtered less than 10 items to display in the suggestion list, it will query the server again for more results. This eliminates the "No Results" errors when you should be getting results.

    Works great for me.. hope this can help someone.

    Posted by: Alexandre B at August 31, 2007 05:36 PM .

    Alexandre B said

    Something else I did to remove the div refresh when the script queries the server, in the CreateList method :

    // create holding div
    var divWasCreated = false;
    var div = document.getElementById("div_" + this.idAs);

    //if the div did not exist before, create it, otherwise, keep the same div object but clear all its child
    if(!div)
    {
    div = _b.DOM.cE("div", {id:this.idAs, className:this.oP.className});
    div.id = "div_" + this.idAs;
    divWasCreated = true;
    }
    else
    {
    while ( div.childNodes.length >= 1 )
    div.removeChild( div.firstChild );
    }

    and a little bit lower in the method

    // add DIV to document
    //
    if(divWasCreated)
    document.getElementsByTagName("body")[0].appendChild(div);

    What this does is before creating the list, it checks if the div is not already created, if it is, it re-uses the same div instead of re-creating another. This effectively removes the list "flicker" when you type. Especially visible when caching is disabled.

    Cheers!

    Posted by: Alexandre B at August 31, 2007 07:58 PM .

    Frank van Eykelen said

    Please note that the info attribute is required, even if it is empty.

    This causes an error:
    <rs id="12112">Airports</rs>

    This works:
    <rs id="12112" info="">Airports</rs>

    And here's the SQL I'm using to generate the XML - for anyone interested in a SQL 2005 / ASP.NET / FOR XML EXPLICIT example:

    SELECT 1 AS Tag, NULL AS Parent
    , NULL AS [results!1!!element], NULL AS [rs!2!!element], NULL AS [rs!2!id], NULL AS [rs!2!info]

    UNION ALL

    SELECT 2 AS Tag, 1 AS Parent
    , NULL, label, id, ''
    FROM imskeywords

    ORDER BY [rs!2!!element]

    FOR XML EXPLICIT

    Posted by: Frank van Eykelen at September 3, 2007 12:53 PM .

    Mike said

    I', trying but still cant make it work with Mysql

    Posted by: Mike at September 4, 2007 07:02 PM .

    aSeptik said

    Hi All! After many tryng i still have problem retrieving data from MySQL! :( All work fine with the hard-coded test.php but i can't make it working with mysql pls pls pls i need help!!

    i need to retrieve just one row from my DB "news_title" and my server don't support XML! :(


    PS: great site, great script, great BSN! ;D

    Posted by: aSeptik at September 5, 2007 01:06 PM .

    tj said

    Very great script. 4 all who are asking to return the id to a hidden field in an xml request. Here is the code. Thank 4 that great script. Just use the callback function.


    var options_xml =
    {
    script: function (input) { return "test.php?input="+input; },
    varname:"input",
    callback: function (obj) { document.getElementById('idst').value = obj.id; }
    };

    var as_xml = new bsn.AutoSuggest('data_xml', options_xml);

    Posted by: tj at September 5, 2007 04:57 PM .

    tj said

    Your form should look like this:


    Posted by: tj at September 5, 2007 05:00 PM .

    Silinde said

    Can someone tell me how I can disable it that, when you press enter (to activate one of the options) that the form submits :P

    Posted by: Silinde at September 6, 2007 10:35 PM .

    James said

    I'm getting an odd error.

    All I've done is dl the example. stick on the local server and changed the test.php to a test.asp page.

    This test.asp page is actually static and generates the following XML (copied from a previous post)

    My Test Venue
    frankvenuetest


    However, whenever I try to run the page.. whenever I enter anything in either search box I get a javascript error.
    The top box generates a "Incorrect Snytax" error (which I suspect is because I'm just using the XML version)

    However the bottom box generates an "object required" problem...

    Anyone offer any help?

    Posted by: James at September 7, 2007 01:58 PM .

    james said

    ignore that - fixed it

    Posted by: james at September 7, 2007 05:19 PM .

    lakhan said

    thanks sir, i need this one in my project but i need little modification in this script.
    i want that if i select one name then it should not came agian in the list , i have done neceessary modifications for that and now i need to pass one more parameter in url (that is selected ids).

    so please tell me how will i do that.
    url:Contacts.php?json=true&selectedIds="+SelectedValue+"&limit=10&"

    i will able to pass SelectedValue in options than it will fit in my application

    thanks

    Posted by: lakhan at September 8, 2007 11:10 AM .

    Emilio said

    Hi! Great script!

    Is there any way to retrieve all suggestions on field focus? I need this to happen in a few inputs. Is it possible?

    Thanks!

    Posted by: Emilio at September 12, 2007 05:28 PM .

    Rui Carmo said

    Hello there! I'm trying out your script as a livesearch replacement, and so far I've come up with three minor niggles:

    - Safari sends double cursor events for some reason (I've noticed a note in your code, but your fix does not seem to work for me).

    - The progressive highlighting is great, but it is designed for highlighting a single word, or a contiguous string (try searching for "Nokia Apple" on my site and you'll see what I mean). This I can live with, and will probably try to turn it into some sort of "relevance" indicator by changing the background color of the text or adding a little bar that scales as characters are "matched"

    - The default behavior of filling in the field when hitting return isn't very useful for live search (you might want to consider adding a callback to allow us to process the return key and choosing what to do with it).

    But all in all, it's a great script. I'll be trying it out for a couple of weeks and see how visitors react, etc.

    Posted by: Rui Carmo at September 13, 2007 07:26 PM .

    James said

    This script is v.good!.
    However I need some advice on the best way of doing the following:

    The results I can search within number 25000!.

    My user is likely to search for fairly generic names (i.e likely to return lots of results).

    Obviously I need to reduce the number of returned to stop the timeouts occuring.. so this is my plan.


    1) - When the script is running (to generate the results) show some kind of wording/graphic to show it's loading.. then when it's done, remove that graphic. (that will stop my user panicing that the page has stopped working

    2) - Show a max of 20 results, but if there are more, show an XML "result" which shows how many other results are there.

    3) - Make that result "clickable" so that it "re-searches" and shows another group of results.

    Some kind of paging of sorts.

    The problem with the above plan is although I have a basic grasp of javascript and AJAX calls, and I'm good with ASP (which I'm coding in.. I haven't a clue where to start with the above.

    can anyone offer any assistance??

    Many thanks in advance!

    Posted by: James at September 14, 2007 12:11 PM .

    James said

    ok, quick update:
    I've managed to get a "loading" img of sorts working, however I'm stuck again!
    This is my script so far:


    var options_xml = {
    script: function (input) {
    document.getElementById('wrapper').className = 'pendingajax';
    return "supplier_po_getstocklist.asp?input="+input+"&SupplierID="+document.getElementById('SupplierID').value;

    },
    //maxresults: 35,
    varname:"input",
    cache: false,
    highlightfirst:true,
    minchars: 4,
    callback:function(obj){document.getElementById('wrapper').className = 'noajaxoperations';},
    noresults: "No Results - Please Add a New Product"
    };
    var as_xml = new bsn.AutoSuggest('testinput_xml', options_xml);


    so when this whole function is ran, before the XML is asked for, a single line changes the class on a div called #wrapper to be visble (ie. show the loading animated gif)...

    then when the callback fires, that class is changed back again (i.e hiding the loading gif)

    all very simple. .and although it works in a fashion.. it has one major flaw...


    The loading img starting to show works fine (i.e it is called before the xml is ran).. however the callback only seems to be fired when the user makes a selection (not when the xml has finished loading).
    So if a user doesn't make a selection from the list, the loading img still shows and it's only when they actually choose something from the list does the callback fire..
    Is that right?

    Posted by: James at September 14, 2007 02:42 PM .

    James said

    ok I've got it working!
    perhaps admin could delete the above posts?

    SIMPLE TUTORIAL -----
    HOW TO ADD VERY SIMPLE LOADING GIF TO SCRIPT
    Step1:
    Make your animated gif and store it

    Step 2:
    On your form page add the following:


    In the css file add the following:

    /* these are custom classes below to shocase a loading img */
    #wrapper.noajaxoperations #imgWait {display:none;}
    #wrapper.pendingajax #imgWait {display:inline;}


    Step 3:
    Finally add the following to the JS file:
    Line 670 should read:
    var pointer = this;

    on the next line add:
    document.getElementById('wrapper').className = 'pendingajax';

    Line 701 (i think) should read:
    this.onComplete( this.req );
    next line add:

    document.getElementById('wrapper').className = 'noajaxoperations';


    you now have a very simple loading img which works on the AJAX call and completion

    (i.e doesn't rely on the callback which only runs when an item is clicked)

    HTH anyone out there and would love to hear of improvements of which I'm sure there are many!

    Posted by: James at September 14, 2007 02:54 PM .

    Emilio said

    Hi James! Nice one! :)

    Can you help me with my question? I think it may be a good implementation to have suggestions on field focus as an option. I'm trying to do it myself but I have little time to work on it right now. :(

    Best,

    Emilio

    Posted by: Emilio at September 14, 2007 09:10 PM .

    W1zzard said

    please add that we can set the width via options:

    if (this.oP.width)
    div.style.width = this.oP.width+"px";
    else
    div.style.width = this.fld.offsetWidth + "px";

    Posted by: W1zzard at September 18, 2007 12:33 PM .

    spamguy said

    Marvellous product, simply marvellous. I downloaded v2.0 and it worked very well. When I upgraded to 2.1.3 (instructions followed, code differences fixed, etc.), the script broke. Firefox reports a syntax error of '()' at line 311...that is,

    var jsondata = eval('(' + req.responseText + ')');
    . I'm sure it's on my end, but I see no HTML or PHP that would bring down this script. Thanks again for this brilliant idea, though!

    Posted by: spamguy at September 19, 2007 07:21 AM .

    Justin said

    i'd like to run a cron script that would rewrite an xml file every 10-20 minutes instead of connecting to the db each time. then the autosuggest could just check the static xml page. Is this possible?

    Posted by: Justin at September 19, 2007 01:36 PM .

    Piskui said

    Hi,
    very nice work! I've try to implement with ASP back-end but don't work!
    The script return "Ajax error: 500".
    Here's my asp code (only test code!!!):




    What's wrong?
    http://www.gruppocrystal.net/ajaxtest/bsn.html

    Thank U!

    PS: Sorry for my English!

    Posted by: Piskui at September 19, 2007 02:41 PM .

    Fer said

    Perfect, perfect, perfect.

    Thank you very much!

    Posted by: Fer at September 19, 2007 09:39 PM .

    spamguy said

    I fixed the above problem. The most likely culprit was that, as I was porting MySQL results to a PHP array, I forgot to define $i, making IDs not work. :P

    I look forward to messing with this some more!

    Posted by: spamguy at September 19, 2007 11:20 PM .

    Piskui said

    All OK! Thanks!

    Posted by: Piskui at September 20, 2007 02:36 PM .

    Primoz Rome said

    Hi Tim,

    very tight script I am using it all over my web application. I have one issue though I would like to address and if anyone can help me with:

    "Completes field when enter key is pressed"
    If I select suggested item with mouse it nicely completes input filed, but if I want to do the same by pressing enter key, my page gets submited with selected parameters send as query string... How can I disable this. I just want to complete inpubox if enter is pressed, without subbmiting anything. Thanks!

    Posted by: Primoz Rome at September 22, 2007 09:11 AM .

    Primoz Rome said

    One more thing... can ID be passed only using JSON (as seen on example page)? I tried to implement the same using XML for my web app but it is not working. Thanks.

    Posted by: Primoz Rome at September 22, 2007 01:26 PM .

    Eradicator said

    Hello,
    I have one problem.
    Everything works fine if I select an item by mouse.
    But if I select an item by pressing Enter key the script also makes the submit of my form to the same url adding a "?" at the end of the querystring.

    Is possibile to only autocomplete when pressin enter, like when I use the mouse?

    Thanks.

    Posted by: Eradicator at September 23, 2007 12:23 AM .

    Eradicator said

    Hello,
    I have one problem.
    Everything works fine if I select an item by mouse.
    But if I select an item by pressing Enter key the script also makes the submit of my form to the same url adding a "?" at the end of the querystring.

    Is possibile to only autocomplete when pressin enter, like when I use the mouse?

    Thanks.

    Posted by: Eradicator at September 23, 2007 12:24 AM .

    Primoz Rome said

    @Erudicator: that's the same problem I am having. Still haven't found work arround. I hope somebody can help.

    Posted by: Primoz Rome at September 23, 2007 03:53 AM .

    Eradicator said

    Found! :-)
    Find this piece of code in the file bsn.AutoSuggest_2.1.3_comp.js
    Around col 806

    window.event.keyCode:a.keyCode;var c=13

    Step a little bit forward and find this:
    switch(b){case c:this.setHighlightedValue();f=0;break;

    Between "f=0;" and "break;" add this:
    return false;

    so the above code will look like this:
    switch(b){case c:this.setHighlightedValue();f=0;return false;break;

    Enjoy! :-)

    Posted by: Eradicator at September 23, 2007 02:35 PM .

    Eradicator said

    Another useful thing will be letting run the script.php not only by GET but also by POST, always from ajax.

    Posted by: Eradicator at September 23, 2007 02:37 PM .

    Primoz Rome said

    @Eradicator: cheers man, thanks for the tip. It works perfectly with enter key now! Yupee.

    Posted by: Primoz Rome at September 23, 2007 09:05 PM .

    miguel said

    Hi, great script.
    I'm trying to do that it works in a more functional way, but I can't. Can someone help me?
    The only thing that I want is that the options appear to the beginning, when I haven't written at all
    Example:
    http://img215.imageshack.us/my.php?image=sinttulo1copiaxi9.jpg

    It is a way of having to very accessible the most used options that the php script returns in xml

    Thanks a lot and sorry for my english

    Posted by: miguel at September 25, 2007 05:03 PM .

    Babu said

    Hi! I am downloded the autosuggest_v2.1.3 on to my local PC, and then I edited the bsn.AutoSuggest_2.1.3.html to changed the script value in the options_xml to point to an XML file containing the data. Then I opened the bsn.AutoSuggest_2.1.3.html page in IE, and typed in a letter in the Person text box under "Example (XML)", and I get a javascript popup error saying "AJAX Error: 0". Can someone tell me how to fix this?

    Thanks,
    Babu

    Posted by: Babu at September 25, 2007 10:34 PM .

    Babu said

    Hi! Has anyone used the autosuggest_v2.1.3 with an XML file as a data source? Looking for a sample code to do this.

    Thanks,
    Babu

    Posted by: Babu at September 26, 2007 03:21 PM .

    great_script said

    Thanks for the great script.
    I'm having issues with users on IE6 using windows NT4 and 98.
    Their browsers never complete loading (removing bsn resolves it) and the autosuggest does not work. Anyone else experienced this?

    Posted by: great_script at September 26, 2007 04:47 PM .

    great_script said

    oh. btw. This is using SSL, same page seems to work fine without ssl.

    Posted by: great_script at September 26, 2007 04:51 PM .

    Marc Miles said

    I have about 200 items that dont ever change, hence not needing the trip to the database but would like these 200 items to be available to the auto complete function. So essentially, the cache would be built immediately on page load and never change. Is it possible to do this with this script, its amazing BTW and I love lightweight js. I'll be giving you a donation as well.

    Posted by: Marc Miles at September 28, 2007 01:28 AM .

    Time Dude said

    Hi there!

    I am confused a bit. I like James' loading gif image but i did not get the part here:

    Step 2:
    On your form page add the following:

    //ADD WHAT?

    Also, what do i do if the page that i wish to go to is not the page that the search is on. In other words, changing the url!

    Cheers,
    TimeDude

    Posted by: Time Dude at October 4, 2007 01:23 PM .

    Jermaine said

    This script really rocks, but one thing seems to be missing in all these scripts or did i miss something?

    i enter the word "town" and the results should be "townsend" as well as "cape town".

    Is this possible - i mean the word should not just start with the entered value it should also contain it. any clue what to do?

    Thanks - appreciate your work ;-)

    Posted by: Jermaine at October 4, 2007 10:40 PM .

    Jermaine said

    I think i was a little too fast with my question. Looks like i shall use the script above where the xml is generated with "input%"?

    I did not look at this as i wrote my own script for this without a LIKE condition. I will take a closer look at it later.

    But i found another thing - the german umlauts. I changed already to iso, but it won't work - even so your "Ä" in the input doesn't work on FF - "no results".

    I grab my data from a database with correct "äöü" and the data is displayed correct - if displayed. So i can see and write "objektmöbel" with the corresponding result, but when i enter "kü" it says no results even if i have entries "küche, kübel, küchengeräte" (they show up with the letter "k" but "kü" says no results

    Posted by: Jermaine at October 4, 2007 11:22 PM .

    Tim said

    Hi bsn/Tim

    Great script got it working in less than 15 mins.
    I was looking to return more information (5 or 6 variables rather than the 3) when using XML. I have looked at the code and tried some mods but none worked. I was wonder if you or anybody else could point me in the right director to get it working.

    Many Thanks

    Tim

    Posted by: Tim at October 9, 2007 02:42 AM .

    Ivan Peevski said

    I have a suggestion to pass on all the information from the returned XML file to the original page.

    Line 329 now says:
    if (results[i].hasChildNodes())
    this.aSug.push( { 'id':results[i].getAttribute('id'), 'value':results[i].childNodes[0].nodeValue, 'info':results[i].getAttribute('info') } );

    Instead it could be:
    if (results[i].hasChildNodes()) {
    attr = results[i].attributes;
    obj = "{ 'value':results[i].childNodes[0].nodeValue";
    for (j = 0; j at = attr[j].name;
    obj +=", '"+at+"':results[i].getAttribute('"+at+"')";
    }
    obj += "}";
    eval('object = ' + obj);
    this.aSuggestions.push( object );
    }

    (Look in the source for the right formatting).

    That way any attribute in the XML file becomes part of the returned javascript object.

    I hope that makes sense. (Contact me if it doesn't).

    Thanks for a great product! :)

    Posted by: Ivan Peevski at October 10, 2007 03:44 PM .

    Ivan Peevski said

    Ops, had a javascript error in the previous post (had copied the change from a previous version).

    The suggested code should be:
    if (results[i].hasChildNodes()) {
    attr = results[i].attributes;
    obj = "{ 'value':results[i].childNodes[0].nodeValue";
    for (j = 0; j at = attr[j].name;
    obj +=", '"+at+"':results[i].getAttribute('"+at+"')";
    }
    obj += "}";
    eval('object = ' + obj);
    this.aSug.push( object );
    }

    Posted by: Ivan Peevski at October 10, 2007 04:03 PM .

    Ian said

    By commenting out this line in getSuggestions, the dropdown behaves much smoother when caching is turned off. It doesn't erase the box, think a bit, then redraw for each letter you type. Instead, it keeps the old one up until the new one replaces it.

    _b.DOM.remE(this.idAs);

    Seems to work ok in Firefox and IE.

    Posted by: Ian at October 10, 2007 08:41 PM .

    Tim said

    Hi Ivan

    I had to modify your code a bit to get it working, but i have now tested this and it works a treat.

    if (results[i].hasChildNodes())
    {
    attr = results[i].attributes;
    obj = "{ 'value':results[i].childNodes[0].nodeValue";
    for (var j=0;j {
    var at = attr[j].name;
    obj +=", '"+at+"':results[i].getAttribute('"+at+"')";
    }
    obj += "}";

    eval('object = ' + obj);
    this.aSug.push( object );
    }

    The above will allow for any number of variables to be returned when using XML.
    This code replaces
    Line 329:
    if (results[i].hasChildNodes())
    this.aSug.push( { 'id':results[i].getAttribute('id'), 'value':results[i].childNodes[0].nodeValue, 'info':results[i].getAttribute('info') } );

    Also many thanks again to bsn for a brilliant bit of code.

    Tim

    Posted by: Tim at October 11, 2007 05:15 AM .

    WIll M said

    Hi...great script sir.

    Several people have talked about this but I am looking for a defined solution. I too wish to take more data back from my DB to the page in the form of other text boxes. My page will be used to search out members and return several pieces of info about them.

    So really what I am looking for is the knowledge of how to make this JSON script carry more pieces of data. Can anyone help?

    will

    Posted by: WIll M at October 14, 2007 03:53 AM .

    mark said

    - - - - - - - - - - - - - - - - - - - -
    Jermaine said

    I think i was a little too fast with my question. Looks like i shall use the script above where the xml is generated with "input%"?

    I did not look at this as i wrote my own script for this without a LIKE condition. I will take a closer look at it later.

    But i found another thing - the german umlauts. I changed already to iso, but it won't work - even so your "Ä" in the input doesn't work on FF - "no results".

    I grab my data from a database with correct "äöü" and the data is displayed correct - if displayed. So i can see and write "objektmöbel" with the corresponding result, but when i enter "kü" it says no results even if i have entries "küche, kübel, küchengeräte" (they show up with the letter "k" but "kü" says no results

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

    MY QUESTION:
    Did anyone that problem?
    because i got the same problem Jermaine had.....
    thx, Mark (euromark @ web.de)

    Posted by: mark at October 20, 2007 07:22 AM .

    BradleyB said

    Has anyone made a mod for this this script to scroll the list if there are so many results that the list goes below the visible portion of the page?

    Posted by: BradleyB at October 20, 2007 11:42 PM .

    mark said

    to BRADLEY B:

    why that?
    in the JS file you can reduce the amount of entries coming up...

    "maxentries: 25"
    e.g.: i reduced it down to 10...

    Posted by: mark at October 21, 2007 05:07 PM .

    patrick said

    terrific job ! The greatest autosuggest around !!!!

    I still would have a newbie question : how could I modify the script so that following a mouse click on a suggestion, the form is not only filled but also submitted ? Something similar as pressing return on a suggestion ...

    thanks a lot in advance for any help !

    Posted by: patrick at October 21, 2007 11:34 PM .

    Ran said

    Great job for the script.
    My company has decided to use your script for our project, however, we ended up rewriting the script with Prototype 6/Scriptaculous and added quite a bit of features. We do,however, want to leave a comment in the script (not commercial script, it will not be sold) stating that it is based on your concept. How would you like us to note it? i'd appreciate if you could get back to me whenever you can. Thanks in advanced. egblue a.t sbcglobal d.o.t net

    Posted by: Ran at October 22, 2007 06:31 AM .

    w1ld said

    great job. thx

    Posted by: w1ld at October 22, 2007 03:45 PM .

    Mark said

    patrick said

    terrific job ! The greatest autosuggest around !!!!

    I still would have a newbie question : how could I modify the script so that following a mouse click on a suggestion, the form is not only filled but also submitted ? Something similar as pressing return on a suggestion ...

    thanks a lot in advance for any help !

    ------------------------------------------------
    I would like the opposit function...
    that it doesnt submit eather way.
    especially not, if you press enter to select a person (by keyboard) not using the mouse at all

    Posted by: Mark at October 22, 2007 11:56 PM .

    Wessam Raafat said

    Hi there,
    Great work, Many thanks.
    The only problem that I faced is the backspace & white space that causes the "No result" message, some of the mates have mentioned the same problem before, I've worked on the Javascript & fixed it, I'm using version 2.1.3.
    Here is the solution, Just replace the getSuggestions function by:
    _b.AutoSuggest.prototype.getSuggestions = function (val)
    {

    // if input stays the same, do nothing
    //
    if (val == this.sInp)
    return 0;


    // kill list
    //
    _b.DOM.remE(this.idAs);


    this.sInp = val;


    // input length is less than the min required to trigger a request
    // do nothing
    //
    if (val.length {
    this.aSug = [];
    this.nInpC = val.length;
    return 0;
    }




    var ol = this.nInpC; // old length
    this.nInpC = val.length ? val.length : 0;



    // if caching enabled, and user is typing (ie. length of input is increasing)
    // filter results out of aSuggestions from last request
    //
    var l = this.aSug.length;
    if (this.nInpC > ol && l && l {
    var arr = [];
    var flag=0;
    for (var i=0;i {
    if (this.aSug[i].value.substr(0,val.length).toLowerCase() == val.toLowerCase())
    {arr.push( this.aSug[i] );flag=1}
    }
    if (flag==0)
    {
    var pointer = this;
    var input = this.sInp;
    clearTimeout(this.ajID);
    this.ajID = setTimeout( function() { pointer.doAjaxRequest(input) }, this.oP.delay );
    return false;
    }
    this.aSug = arr;
    this.createList(this.aSug);
    return false;
    }
    else
    // do new request
    //
    {
    var pointer = this;
    var input = this.sInp;
    clearTimeout(this.ajID);
    this.ajID = setTimeout( function() { pointer.doAjaxRequest(input) }, this.oP.delay );
    }

    return false;
    };

    What I did is just telling the function to create a new request if the typed letters are not in the list, please look at the flag variable & you should realize what I did.
    Enjoy!
    Wessam

    Posted by: Wessam Raafat at October 24, 2007 07:40 AM .

    mark said

    great idea, Wessam
    i have the same problem with whitespacess and the backspace key.

    but the mod from you didnt work for me..
    dont know why, i've got the same version

    Posted by: mark at October 25, 2007 01:52 AM .

    Maddy said

    Can any one provide a sample for asp.net application.
    I just cant get it working :-(

    Posted by: Maddy at October 26, 2007 06:32 AM .

    Drew said

    I downloaded the latest version (v2.1.3) and tried out the demo code that came with it, but it returns 'AJAX error: 0' every time. Does anyone know what the problem is?

    By the way, I'm running Apache 2.2 on Windows XP.

    Thanks,
    DrewP

    Posted by: Drew at October 26, 2007 10:03 PM .

    neil said

    Great work,

    I am trying to get it to work liiking at a database and i am not to sure how to get it working.

    i have tryes puting this code in insted of the array :
    $result = mysql_query("SELECT * FROM person");
    $aUsers = array();
    while ($row = mysql_fetch_array($result))
    {
    $aUsers[] = $row['FullName'];
    }

    but it dosent seem to work.

    any ideas.

    Neil

    Posted by: neil at October 29, 2007 06:28 PM .

    Mathijs said

    Hi Tim,

    First of all i'd like to say that his is a great script.

    I have a question. It's probably really easy for you but i can't seem to find the solution. I'd like to show two more extra fields that will be autofilled when a name is clicked.

    For example there are three fields
    1. Name
    2. Address
    3. Location

    If a name, let's say Tim, is clicked in the two fields below the address and the location appear that are connected to tim.

    I tried to move it to the idfield but i only get one character there and then iam ofcoarse still missing 1 field. Could you help me out?

    Thanks in advance!

    Posted by: Mathijs at November 7, 2007 01:42 AM .

    William said

    Nice work! this is really useful and thanks for that. However, I'd wish to make one suggestion for you: May you put an image into textbox to indicate when a request is going on?. Moreover, I'm having one problem using your control cache, sometimes after making a request (which I get a record set) I delete one character and get the message "No results", so I gotta delete another character else or delete whole text or write one extra character to get a new record set, I resolved this disabling the cache. I believe that your work can be much better if you extract some ideas from other authors like createwebapp.com's widget which is another nice work.

    Posted by: William at November 7, 2007 06:00 PM .

    Tonydspaniard said

    Hi there, first of all, great job my friend and thank you very much for posting it... With your permission, I did some changes on your script to work with prototype and scriptaculous... also, found out that when pressing the RETURN KEY, the fields are posted instead of writing the value to them. In order to properly cancel the event bubble i suggest you add the function:

    function stopBubble(e)
    {
    if (e.preventDefault) {
    e.preventDefault();
    e.stopPropagation();
    } else {
    e.returnValue = false;
    e.cancelBubble = true;
    }
    }

    this will prevent the event to continue and post the forms.

    In addition, I added the TAB feature to it. It needs to be added on the KeyPress:

    AutoSuggest.prototype.onKeyPress = function (e)
    {
    if (!e) e = window.event;

    var key = e.keyCode || e.wich;

    switch(key)
    {
    case KEY_RETURN:
    this.setHighlightedValue();
    stopBubble(e);
    break;
    case KEY_TAB:
    this.changeHighlight(key);
    stopBubble(ev);
    break;
    case KEY_ESC:
    this.clearSuggestions();
    break;
    }
    return true;
    }

    Regards... and thank you very much again

    Posted by: Tonydspaniard at November 8, 2007 02:34 PM .

    James said

    TAB key not work on ie7 ?

    Posted by: James at November 9, 2007 04:32 PM .

    Tonydspaniard said

    Hi bsn, because i wanted to adapt your script to my current work i have written a version of your script that works together with prototype 1.5.1 and scriptaculous 1.7.1. (user could actually set the way the dropdown is displayed by any of the effects).. extended its properties and cleaned the code in some areas. Also, i have included an icon notifier exactly as createwebapp.com and the option to display it or not... i love your widget and i would like to cooperate to increase its usability... if you are interested please contact me at the email posted on this comments... thank you very much again for your generousity (script) and efforts (free development)

    Posted by: Tonydspaniard at November 9, 2007 07:48 PM .

    costas said

    Hello!! great work! it look fantastic..
    but ( there is always a "but") i cannot seem to make it work with other encodings.
    the test.php is in Latin 1 encoding-I believe-...when I change it to UTF-8, in order to accept my Greek keywords, it still works for everything is written in english but it doesnt do the match for the Greek words.
    I havent tested with mysql because my keywords are going to be quite static so i dont need a db.

    Any thoughts?I know that I am doing something wrong but i cant seem to find it!!!!!

    Posted by: costas at November 13, 2007 05:55 PM .

    costas said

    cool!!I made some changes and it workd..
    seems that the utf8_decode was useless...anyway..
    now some other question...
    do you think you can give me some quidelines on how to have 3-4 textboxes with the same functionality in the same page but each one working with a different dictionary(keywords)?

    sorry for the multiple questions..
    cheers mate!

    Posted by: costas at November 13, 2007 07:27 PM .

    mathijs said

    Tonydspaniard said

    Hi bsn, because i wanted to adapt your script to my current work i have written a version of your script that works together with prototype 1.5.1 and scriptaculous 1.7.1. (user could actually set the way the dropdown is displayed by any of the effects).. extended its properties and cleaned the code in some areas. Also, i have included an icon notifier exactly as createwebapp.com and the option to display it or not... i love your widget and i would like to cooperate to increase its usability... if you are interested please contact me at the email posted on this comments... thank you very much again for your generousity (script) and efforts (free development)

    Hi Tony. You seem to know a lot about it as well. Could you perhaps help me out. I've been trying to do the stuff below for ages but it doesn't work. There are three files and i don't know what to edit where..

    Mathijs said

    Hi Tim,


    First of all i'd like to say that his is a great script.


    I have a question. It's probably really easy for you but i can't seem to find the solution. I'd like to show two more extra fields that will be autofilled when a name is clicked.


    For example there are three fields
    1. Name
    2. Address
    3. Location


    If a name, let's say Tim, is clicked in the two fields below the address and the location appear that are connected to tim.


    I tried to move it to the idfield but i only get one character there and then iam ofcoarse still missing 1 field. Could you help me out?


    Thanks in advance!

    Posted by: mathijs at November 14, 2007 12:16 AM .

    Tonydspaniard said

    Hi there again, Hi mathijs...

    I have started a blog and posted the results of my work to share with you guys...

    The blog is located in: http://webeaters.blogspot.com

    ---------------
    Hi there Mathijs, if that is the problem you have I recommend you to look in another possibility:

    in setSuggestions function you see that the array aSug is filled with the objects (whether in json or xml). it is there where you add extra fields (remember to change the PHP file to push the extra fields in this case).

    then, to recover the value, go to setHighlightedValue function in order to access your extra field (location for example -aSug[iHigh-1].location)

    -----------

    check out my object, it does work with prototype and have a more dynamic object creation...

    Posted by: Tonydspaniard at November 14, 2007 10:27 AM .

    Charlie Farrow said

    I like the script; it looks good.

    I tried to test it, I uploaded the unziped files into my webspace and chmod them all to 777. then i ran the test html page in a web browser and started to type and all i get is "AJAX Error: 0"

    Anyone know what causes this?

    Posted by: Charlie Farrow at November 14, 2007 11:30 AM .

    Charlie Farrow said

    Charlie Farrow said

    I like the script; it looks good.

    I tried to test it, I uploaded the unziped files into my webspace and chmod them all to 777. then i ran the test html page in a web browser and started to type and all i get is "AJAX Error: 0"

    Anyone know what causes this?

    In my silly case it was because the browser was not using HTTP to access the file on the local web root! Now it works fine! Sorry to mess up the board!!

    Posted by: Charlie Farrow at November 14, 2007 11:38 AM .

    adazas said

    I need to know where I have to alter the code to define the number of results can be viewed at suggest. And you see a scroll bar (overflow: auto).

    Please anyone can help,

    Adazas

    Posted by: adazas at November 14, 2007 12:21 PM .

    Pete said

    My agency is looking for ways to enhance a knowledgebase's keyword search field with auto-completion, as a way of reducing failed searches due to poor spelling.

    Could this tool, Ajax Auto Suggest, be used with the open source Spell Checker "GNU Aspell" (http://aspell.net/)?

    - Pete

    Posted by: Pete at November 14, 2007 05:55 PM .

    jonas said

    Hi and thanks for the wonderfull script.
    Im trying to figure out on how to get both the value and the info as a result.

    ie, when looking for a user in the example, you get the dropdown list, and in that list you have the country.

    When choosing the user from the slick 2.0(ish) dropdown, i would like it to insert the country/city aswell in the input field. Any nice ways of going about that?

    Kind Regards, from sweden.

    Posted by: jonas at November 15, 2007 09:36 AM .

    arun said


    Hi and thanks for the wonderfull script and tips
    I just narrate my problem
    i just modify the css

    "overflow: auto;
    width:215;
    height:150;"
    inside then class called "div.autosuggest ul"
    Scroll is appeared.
    i can scroll list using mouse .
    My problem is in keyboard.
    Since i fixed the hight i cannt scroll and view div content .Pls guide me how to solve this problem

    Posted by: arun at November 16, 2007 01:21 PM .

    arun said

    Hi and thanks for the wonderfull script and tips
    I just narrate my problem
    i just modify the css

    "overflow: auto;
    width:215;
    height:150;"
    inside class file called "div.autosuggest ul"
    Scroll is appeared.
    i can scroll list using mouse .
    My problem is in keyboard.
    Since i fixed the height i cannt scroll and view div content .Pls guide me how to solve this problem

    Posted by: arun at November 17, 2007 05:00 AM .

    arun said

    Hi and thanks for the wonderfull script and tips
    I just narrate my problem
    i just modify the css

    "overflow: auto;
    width:215;
    height:150;"
    inside class called "div.autosuggest ul"
    Scroll is appeared.
    i can scroll list using mouse .
    My problem is in keyboard.
    Since i fixed the hieght i cannt scroll and view div content .Pls guide me how to solve this problem

    Posted by: arun at November 17, 2007 05:01 AM .

    Keege said

    Any possibilities to make script work straight out of the box?

    Like this:

    <input type="text" onkeyup="autofill()" />

    It would easier things alot. Thanks for the nice script anyways.

    Posted by: Keege at November 18, 2007 09:19 PM .

    Chris said

    Hi Sanjay,

    Ever get this going. Would you be able to provide your code as well please.

    Cheers
    Chris

    Sanjay said

    Hello Everybody,
    I have been trying to configure this beautiful piece of code using ASP. But i am getting error.Please have a look at my code and help me. I have replaced opening and closing tags with ( and )


    ****bsn.AutoSuggest.html****


    (html)
    (head)
    (title)Ajax auto-suggest / auto-complete | BrandSpankingNew(/title)



    (script type="text/javascript" src="js/bsn.AutoSuggest_c_2.0.js")(/script)


    (link rel="stylesheet" href="css/autosuggest_inquisitor.css" type="text/css" media="screen" charset="utf-8" /)


    (/head)
    (body)


    (div id="wrapper")
    (div id="content")


    (h2)Example (XML)(/h2)


    (div)
    (form method="get" action="")
    (label for="testinput_xml")Person(/label)
    (input type="text" id="testinput_xml" value="" style="width:300px" /)
    (br /)(br /)(input type="submit" value="submit" /)
    (/form)
    (/div)
    (script type="text/javascript")


    var options_xml = {
    script:"test.asp?",
    varname:"typing"
    };
    var as_xml = new AutoSuggest('testinput_xml', options_xml);
    (/script)


    (/body)



    ****test.asp****
    (%
    typing = LCase(Request("typing"))

    Set objconn=server.createobject("adodb.connection")
    objconn.open "Provider=sqloledb;Server=Servername;Database=DBName;UID=sa;PWD=pwd;"
    set objrecord=server.createobject("adodb.recordset")



    set objrecord=objconn.execute("SELECT TOP 10 records FROM tablename WHERE CHARINDEX ('"&typing&"', records)) 0 ORDER BY CHARINDEX ('"&typing&"', records)")


    if objrecord.eof or objrecord.bof then


    Response.Write "Oops Not Found"
    response.end
    else



    end if


    Response.ContentType = "text/xml"


    Response.write "(?xml version=""1.0"" encoding=""utf-8"" ?)(results)"
    do while not objrecord.eof
    i=i+1
    Response.write "(rs)"&objrecord.fields("Vilname")&"(/rs)"
    objrecord.movenext
    loop
    Response.write "(/results)"


    %)

    Posted by: Chris at November 19, 2007 01:27 AM .

    Daniel said

    Hi,

    The autosuggest works great! However i have one problem which i can't seem to figure out! If i do a ajax request after the autosuggest has completed and put the value into the textbox the auto suggest ceases working on any thing else i have typed into the box after that ajax request. Any ideas?

    Posted by: Daniel at November 19, 2007 12:37 PM .

    Scott H said

    I love the autosuggest! I've successfully been using it within some jsp code. I've been trying to integrate the autosuggest capability within some extjs 2.0 javascript code but have run into a small problem. My application utilizes a popup window from the extjs framework. The window contains various input fields from which I'm trying to invoke autosuggest. It works but the drop down list created by autosuggest is partially obscured behind the popup window. Any ideas how I can get the autosuggest list to render in front of the popup window rather than behind it?

    Many thanks in advance,
    Scott

    Posted by: Scott H at November 19, 2007 08:44 PM .

    arun said

    Pls solve my problem
    I just narrate my problem
    i just modify the css

    "overflow: auto;
    width:215;
    height:150;"
    inside class called "div.autosuggest ul"
    Scroll is appeared.
    i can scroll list using mouse .
    My problem is in keyboard.
    Since i fixed the height .i cannt scroll and view div content .Pls guide me how to solve this problem

    Posted by: arun at November 20, 2007 05:19 AM .

    Matt said

    This looks awesome thanks.

    I'm wondering however if it's possible to use this with dynamic inputs.
    For example, I have a small prototype window that the user can enter some input. If they want to add more than one item they can click an add button which will add a new row. I can get the autosuggest to come up with the very first row (it's not dynamic), but anytime I add a new row I can't get it to work. Do you know how this would be possible?

    Here's the detail. I have a button that calls a javascript function createRow. In the create row I do something like this:

    var cell = row.insertCell(1);
    var el = document.createElement('input');
    el.setAttribute('type', 'text');
    el.setAttribute('name','rollupName');
    el.setAttribute('value', '');
    el.setAttribute('size', '10');
    el.setAttribute('maxLength', '64');
    el.setAttribute('id', "input_" + lastRow);
    el.onchange = function (evt) { checkValidRollup(lastRow) };
    cell.appendChild(el);

    I then try to add an autosuggest box to it. That's the part I'm confused at. I don't even know if it's possible.

    Thanks.

    Posted by: Matt at November 20, 2007 09:57 PM .

    Suchi Garg said

    Hello
    First of all thanks for this wonderful script.
    It is working fine for me except for one issue - I sometimes get "No results!!" even when i know that i have results in the DB. When i change the pace of my typing - the results show up.
    My guess is that this happens when the keypress and the keyup events somehow mess with each other.
    Has anyone else got this issue? Can you suggest a solution.
    As a possible solution to my problem - is it possible to "activate" the script say after a certain time period has passed after the user has stopped entering in the text box. (This means that when the user writes something into the text box and pauses for a very small amt of time - we show the auto suggest options at that time instead of showing them on every key press) I know just very basic JS - so dunno if that is possible or not.

    Thanks
    Suchi

    Posted by: Suchi Garg at November 22, 2007 05:15 AM .

    Asanka said

    i have download the script.
    but when im tryin to run it from my local comuter it gives me AJAX error... do i need to do any modifications for this after downloading.?

    thnx..

    Posted by: Asanka at November 24, 2007 11:06 AM .

    Matt said

    Hi,

    Im having problems getting the forms to submit when pressing Enter..
    The autosuggest is working great - just it seems I cannot submit the form using the Enter button anymore.

    Is there something I have to activate within the options?? Im using image inputs for my submit buttons

    Would appreciate any help.

    Matt

    Posted by: Matt at November 27, 2007 01:17 AM .

    david said

    can someone show me how to use this for classic asp?

    Posted by: david at November 27, 2007 06:42 AM .

    Brian said

    I have set up a script to look for the beginning part of any word in the array, but every other key stroke will remove the word that you are searching for.

    Here is the link to the site that I'm testing. Use the keyword "lutheran" to see an example that I'm talking about. It only displays the searches with "lutheran" when your keyword is "l","lut","luthe", or "luthera"

    I'm not really sure why it skips over like that, so if anyone has any advice, it would be greatly appreciated.

    Thanks,
    Brian

    Posted by: Brian at November 27, 2007 09:31 PM .

    Paul Jennings said

    hiya,

    Fantastic script! Just what I was looking for. I have implemented this at www.ukfindit.com (UK Search Engine) to auto suggest what people want to search for.

    It works REALLY well!!

    Thanks!

    Posted by: Paul Jennings at December 1, 2007 12:49 PM .

    Kevin said

    Thanks for the great script. I seem to be having the same problems as some of the other lads. I am using this script to interogate the database for a list of users - currently there are over 35K of them and it handles it really well :) Like i said - great script.
    I pull back names, id and DOB and display the ID in the hidden field - the problem i have is that i cant get it to display on the page i submit the form to.

    Any ideas?

    The setup is pretty much the same as before.. the only difference is that i am pupulating the array with responses from the sql query as opposed to a straight array of values.

    Even to pass the id or name or info valuues in the get would be great as i can get the details then in the next page.

    I am using php scripting to attempt this.

    Thanks

    Posted by: Kevin at December 4, 2007 04:31 PM .

    TylerEss said

    Our application was doing word splitting on the search query and returning results where the matches on the split words were discontiguous... the "turn the matches blue" code had a fit!

    Here's a simple example:
    search query: "ap ter"
    results: "Apple Terminal", "Napster", "Application Interface"

    I reworked it to handle discontiguous matches; it's a little slower now due to the regular expression usage, but it seems to be working well. Also, note that it can write silly em tags when search term words overlap, such as when you search for "Auto utoSuggest" and find "AutoSuggest"...

    Here's the diff:

    --- bsn.AutoSuggest_2.1.3.js Tue Dec 4 16:41:02 2007
    +++ bsn.AutoSuggest_2.1.3.js.updated Tue Dec 4 16:40:53 2007
    @@ -402,9 +402,13 @@
    // (as HTML, not DOM)
    //
    var val = arr[i].value;
    - var st = val.toLowerCase().indexOf( this.sInp.toLowerCase() );
    - var output = val.substring(0,st) + "" + val.substring(st, st+this.sInp.length) + "" + val.substring(st+this.sInp.length);
    -
    + var sa = this.sInp.replace(/^\s+|\s+$/g,"").replace(/\s\s+/g," ").split(" ");
    + for ( var j=0;j + {
    + var re = new RegExp("("+sa[j]+")","gi");
    + val=val.replace(re,"$1");
    + }
    + var output = val;

    var span = _b.DOM.cE("span", {}, output, true);
    if (arr[i].info != "")

    Posted by: TylerEss at December 4, 2007 11:52 PM .

    HroSCeK said

    Hey..

    First of all -> this is THE BEST script for auto suggestioin around! Congratulations for that..

    But, i have a little problem.. I know this is only to complete one object in form but i need something extra but I don't know how to make it. When I click on the item I want to select, I want it to complete two fileds..
    Let's say I have a list of people with birthday dates (I don't but let's say I do :) ).. Now, when I select a name I want the first field with AutoComplete script to fill with name from XML and a field lower (let's say it's name is "date_field") to be filled with the date.

    I hope you understand what I need.. Is this even possible? I could add something in XML list (it is populated with MySQL) so there would be no problem.. I tested a lot of things but nothing worked! Suggestions?

    Posted by: HroSCeK at December 6, 2007 08:03 AM .

    Val said

    Very nice thank you!

    I do have a question:

    Can you send me a full version with MYSQL sample and not a array include in test.php

    Posted by: Val at December 6, 2007 07:04 PM .

    Printoo said

    Hi
    Ihave a problem with my code
    Thanks for your help!


    test.php
    [code]

    [/code]

    and in html webpage
    [code]

    Hidden ID Field:
    Company




    var options = {
    script:"autosuggest/test.php?json=true&limit=6&",
    varname:"input",
    json:true,
    shownoresults:false,
    maxresults:6,
    callback: function (obj) { document.getElementById('testid').value = obj.id; }
    };
    var as_json = new bsn.AutoSuggest('testinput', options);

    [/code]

    Posted by: Printoo at December 6, 2007 08:44 PM .

    BC]Fasty said

    I have to say: nice script, if not the best around (i've tried many of them *g*) !!!

    Continue your great work!

    Posted by: BC]Fasty at December 11, 2007 03:20 PM .

    Jim said

    I replaced the code on line 329, but I'm getting an error. "line 81...bsn undefined"

    Can someone help? Thanks!


    Tim said

    Hi Ivan


    I had to modify your code a bit to get it working, but i have now tested this and it works a treat.


    if (results[i].hasChildNodes())
    {
    attr = results[i].attributes;
    obj = "{ 'value':results[i].childNodes[0].nodeValue";
    for (var j=0;j {
    var at = attr[j].name;
    obj +=", '"+at+"':results[i].getAttribute('"+at+"')";
    }
    obj += "}";

    eval('object = ' + obj);
    this.aSug.push( object );
    }


    The above will allow for any number of variables to be returned when using XML.
    This code replaces
    Line 329:
    if (results[i].hasChildNodes())
    this.aSug.push( { 'id':results[i].getAttribute('id'), 'value':results[i].childNodes[0].nodeValue, 'info':results[i].getAttribute('info') } );


    Also many thanks again to bsn for a brilliant bit of code.


    Tim

    Posted by: Jim at December 14, 2007 01:17 AM .

    Simran said

    Hi,
    I am getting Ajax Error 1.
    Can u please help me out with it.

    Regards,
    Simran

    Posted by: Simran at December 14, 2007 12:19 PM .

    Chango said

    HI i'm ussing this:

    John Smart said

    This is a very basic piece of code that may help someone get going. Have the script point to this file


    header ("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); // Date in the past

    header ("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); // always modified

    header ("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1

    header ("Pragma: no-cache"); // HTTP/1.0

    header("Content-Type: text/xml");

    echo'';# this is the xml version and encoding tag - I am unable to psost that here, so copy the one from the downloaded file.

    include 'includes/config.inc.php';

    # We are to select what we want, and represent it as:

    #foo

    # Test for completness

    $limit=2;

    $tested=$_GET[input][0].$_GET[input][1].$_GET[input][2];

    if (strtolower($tested)=='the')

    {

    $limit=5;

    }

    if (strlen($_GET[input])>$limit)

    {

    #

    $sql='SELECT * FROM artist WHERE name LIKE "%'.$_GET[input].'%"';

    $result = @mysql_query($sql,$connection) or die ('Issues with artist '.$sql);

    while ($row = mysql_fetch_array($result))

    {

    $display.=''.$row[name].'

    ';

    }

    #

    }

    echo''.$display.'';

    ?>

    This limits the search to three characters UNLESS the 1st three characters are 'the' - because that could get messy - this is to list artists from a sql database. The missing include file simply sets the sql connection details. This is a very sloppy bit of code. When I get it tidied up I will resubmit it. If you tinker, and see javascript errors, then you have a php error! It is shown as a javascript error because the java script cannot handle a php error (I know how it feels!)

    Again, than you for supplying this code, I could not have written it, and see uses for it in almost every site I work on!

    Larry said

    Outstanding work Tim... I'm sure you hear that a lot, but it really is a beacon of quality.. :)

    I've found the script to be a little slow compared to others... so wondered if it might be the size of the JS code. Is there anything one can cut out to make it a leaner script. I'm using the XML portion exclusively for instance. Does the JSON code make any improvement to performance?

    For the PostgreSQL guys... here's my snippet of code for getting 2 fields from the database. Hope it helps:

    ("header" stuff as normal follows this)

    $input = strtolower( $_GET['input'] );
    $len = strlen($input);
    $aResults = array();

    if ($len)
    {
    $db = pg_connect('your DB');
    $qu = pg_query($db, "your QUERY");

    $i=0;
    while ($row = pg_fetch_row($qu))
    {
    if (strtolower(substr($row[0],0,$len)) == $input)
    {
    $aResults[] = array( 'id'=>($i+1), 'value'=>htmlspecialchars($row[0]), 'info'=>htmlspecialchars($row[1]) );
    $i++;
    }
    }
    pg_free_result($qu);
    }


    BUT THE PROBLES IS THAT áéíóúñ shows " ? ", how can i work from MYSQL and titles?

    Posted by: Chango at December 15, 2007 12:32 AM .

    Chango said

    HELP, i can't search áéíóú for MYSQL query!
    Please any help! i really need this.

    Posted by: Chango at December 15, 2007 03:37 AM .

    jose said

    I downloaded the latest version (v2.1.3) and tried out the demo code that came with it, but it returns 'AJAX error: 0' every time.
    Does anyone know what the problem is?

    Posted by: jose at December 15, 2007 06:41 PM .

    Ken said

    When using a website with frames, the search suggestions is only displayed partially. For example, I'd like to use the autosuggest on this page:

    http://zoek.net/queries/perform?w=1&q=autosuggest

    Is there any way around this problem?

    Posted by: Ken at December 15, 2007 08:15 PM .

    Xian said

    Hey there,
    GREAT JOB! I LOVE IT.

    So...I'm using struts (Java) I get the result into my 'livesearch' dev id, (and I have reference to the /css and /javascript files) and the result comes as XML

    for some reason, the results comes without the frame and I don't have the ability to click on any result (it's a plain text).

    thanks for any pointers

    Posted by: Xian at December 18, 2007 01:25 AM .

    Zap said

    @HroSCeK:
    just fill the callback with a function call instead of a single command:

    callback: function (obj) { doSomethingWith(obj); }

    and create a function to handle the result

    function doSomethingWith(obj){
    name = obj.value;
    date = obj.info;
    }

    Posted by: Zap at December 18, 2007 12:57 PM .

    Kevin said

    Hey Zap
    I tried to do what you suggested there now -


    function doSomethingWith(obj){
    person_id = obj.id;
    person_name = obj.value;
    person_dob = obj.info;
    }

    and invoke this in the callback function but when i try to call this callback function the script stops working.

    I dont know javascript that well. But once i remove the text input that is being used for the search field it no longer works.

    Is there any way that i can leave the original callback in place yet modify it to take additional varaibles...

    My problem is that on top of the name value being passed I also need the id to be passed so i can store in a db.

    Also can you suggest where i place the JS code. At the moment i am including , with php, the html form fields inside another form that is then being processed and sent onto a script that will extract and send the info to a db.

    Thanks for your help
    Kevin

    Posted by: Kevin at December 18, 2007 10:04 PM .

    Jim said

    I am stuck. Please help.

    Is there a way that I can enable/disable auto suggest on a input box by a selection of 2 radio buttons?

    if radio "a" is selected, auto suggest is enabled on input box "input"
    if radio "b" is select, auto suggest is disabled on input box "input"

    I tried reassigning the as_xml variable to some other field to disable it on "input" but it doesn't take it. Suggest still works on the input box.


    function goto_URL(ctrl)
    {
    if(ctrl.value=="People"){
    alert(ctrl.value);
    var as_xml = new bsn.AutoSuggest("testinput", options_xml);
    }
    else {
    var as_xml = new bsn.AutoSuggest("test", options_xml);
    }
    }

    Posted by: Jim at December 19, 2007 10:03 AM .

    geo said

    Hi I want to use the script on my site, but after several tests couldnt make it work. I want the script to retrieve data dynamically from the database, the address of the search function is index.php?do=search what i have to change? Thanks for the input, cheers
    Geo

    Posted by: geo at December 19, 2007 06:43 PM .

    Erick said

    Hi,

    Great script!
    I got almost everything working. I can read the user information with a mysql connection into the suggest box. The only problem is de ID, the scripts puts it in the hidden ID field. Is it possible to get this into a variable and insert it into the DB?

    Thanks in advance,

    Erick

    Posted by: Erick at December 19, 2007 11:49 PM .

    Olmec said

    Like the script. I got it to work in firefox but in IE I get an object error when it tries to parse the XML results. I had to modify the script because I found (in firefox) that the XML result was in the responseText property, not resultXML

    Any Ideas?

    Posted by: Olmec at December 20, 2007 10:11 PM .

    Olmec said

    ok! So I fixed my issue after a bit more research...

    The general issue is (I think) that my results are coming back from the service as xml.resultText and then I have to do an IE / FF check and then either use the IE loadXML function or the FF DOMParser system....

    Works for me, I'm happy :)

    Posted by: Olmec at December 20, 2007 10:23 PM .

    Manesh said

    Hello,
    I have everything working with XML, however when I hit submit, nothing is getting sent to POST. Anyone have an idea on what could be causing it?

    Posted by: Manesh at December 29, 2007 04:17 AM .

    Igor said

    Hi.

    Cool script.

    Only one thing.
    In function onKeyPress bubble must be boolean instead int. Because when user presses enter, this event should not be handled by the form.
    If it returns 1 or 0, like it is now, then form is submitted, which is not always good.

    _b.AutoSuggest.prototype.onKeyPress = function(ev)
    {
    ...
    var bubble = true;
    ...
    case RETURN:
    this.setHighlightedValue();
    bubble = false;
    ...
    return bubble;
    };

    Posted by: Igor at December 29, 2007 04:23 PM .