This page has changed location!!!!
Please go to http://www.ramirezcobos.com/labs/ajax-powered-autocomplete/
Thursday, November 15, 2007
AJAX - Powered AutoComplete (for Prototype.js)
Subscribe to:
Post Comments (Atom)
The content of this blog is published under a Creative Commons License | RSS Feed |
81 comments:
XML Example not working for me. In the test.html, when i type "a" in the input field, nothing appears.
Anybody else?
Hi 'a',
Thanks for reporting such issue but after looking at the code of test.html I had no problems at all.
What is the browser you have test it with?
If you use Firefox, do you firebug it?
Muy bueno, ¿has usado alguna vez Mootools? es una alternativa a Prototype.
Tienes más info en mi blog.
Saludos
Lo he probado con Firefox y funciona bien, En IE no, ni v6 ni v7
Salu2
Hola Sito,
Lamentablemente estoy en Mac, funciona en Safary y Firefox en Mac, sin embargo no he podido utilizar nada en Windows ya que programo en Mac. Alguna posibilidad para averiguar cual es el problema desde tu ordenador?
Saludos
Hola Tony,
Lo he probado, y efectivamente ahora funciona correctameten con IE (6 y 7) también.
Buen trabajo.
Salu2
Tab key for jumping to the next field of the formular won't work in the newest FF.
Any Ideas?
cheers
fanfa
Hi there fanfarian,
This is the FF (MacBook Pro OSX Intel) version I tried the component with: Mozilla/5.0 (Macintosh; U; Intel Mac OS X; es-ES; rv:1.8.1.11) Gecko/20071127 Firefox/2.0.0.11, and it works as expected.
Could you firebug it? and see what is happening?
This is how we adopt the onkeyup and onkeypress events our functions:
// NOTE: not using addEventListener because UpArrow fired twice in Safari
this.fld.onkeypress = function(ev){ return p.onKeyPress(ev); };
this.fld.onkeyup = function(ev){ return p.onKeyUp(ev); };
----
Another way to do it is with the Event.observe prototype's function but I did not have any problem...
----
Let me know if you continue with same issues, we could try to change it to Event.observe
Hi
I search full version ok with Mysql query.
Do you a stable version ?
Val
Hi Tony,
more in detail ;)
The problem is not with the autocomplete, it works fine.
I have a formular with 2 input fields, both with autocomplete (works fine together).
In FF I can't jump to the next input field using the tab-key, in IE6+7 I can.
cheers
fanfa
Saludos, estoy probando el script y funciona muy bien. Tendran por casualidad un ejemplo para llenar los array con data de una BD?
Estoy probando pero no he logrado hacerlo correctamente. Si tienen algo que me puedan recomendar para el PHP y la BD se los agradeceria.
Saludos,
Tony ya resolvi lo de la BD ahora el problema que tengo es que yo necesito muchos campos con el autocomplete en un mismo formulario. Hay alguna forma sencilla de hacerlo?
Saludos y gracias,
Hola Juan,
Cuando dices que necesitas muchos campos con el autocomplete a qué te refieres? cuando hablas de muchos campos, quieres decir que quieres mostrarlos en la lista?
Es tan sencillo como hackear el código XML o JSON en el servidor o incluso, cambiar las respuestas para que estas sean reconocidas en el autocomplete y ponerle un ancho (que se puede hacer) que se adecue a las nuevas necesidades de la petición...
Saludos y dime cosas...
Tony, a lo que me referia era a poder tener varios campos que usen el autocomplete en el mismo formulario; pero eso ya esta resuelto tambien.
Ahora un error que parece simple pero no consigo el origen. El ventiladorcito del autocomplete_spinner no me sale en el campo cuando esta pensando.
Todo el resto del estilo lo toma sin problemas y ya esta funcionando todo menos eso. Tuve que quitar algunos estilos del CSS que me daban conflicto con el CCS de mi sitio pero no veo que hagan referencia nunca al spinner. La lupa si se ve correctamente al igual que el resto de las imagenes. Es solo esa la que no se muestra.
Alguna idea?
Saludos y gracias,
Bueno resuelto eso tambien. No note que habian enlaces a las imagenes en el javascript.
Cualquier otra cosa paso por aqui.
Saludos,
When trying to use XHTML Doctype, style is not applied to the selection box. Any idea why ?
Hi Cedric,
I do not think that the CSS problem has something to do with your docType decision. Check on your css references and if the images path of the CSS is correct.
No, I'm sure as when I remove the doctype it works perfectly.
please tony where réda from because i'm in algeria exactly in blida...juste 30 kilo from hajdout lol...say thanks to it ;) and to you for you nice script !
aniss1230@gmail.com
Hi TOny
Great script but I'd like to set a URL beneath the items that get listed that points to a relative location. Where di I start to look please?
Hi anonymous,
You can modify the values listed within the service file (PHP in the example). info tags can be replaced with links.
Or you can do it on the function createList at this location:
if(arr[i].info != '') // do we need to add extra info?
{
var br = Core.Util.createDOMElement('br',{});
span.appendChild(br);
var small = Core.Util.createDOMElement('small',{}, arr[i].info);
span.appendChild(small);
}
Hope this helps you...
Excellent! Works great and I'm no JS expert...
In fact I simply modfied line 341 to the following:-
var a = this.createDOMElement('a',{href:'myurl/ID,' + arr[i].id});
Big thanks ...!
Really Exellent work sir.
Thanx for the code
I am .NET guy. I don't know javascript and don't know PHP :(
I tried to make MyPage.aspx instead of Test.php. In MyPage.aspx, I generated XML file and written it by Response.Write(). When i pass Query sting to Test.php and MyPage.aspx, result is same. But I am not able to use it in test.html file. Can anyone guide me how to use in .NET ?
I think that id you speaks Spanish, you may contribute with the explanations using Spanish. It dificults the progress of the people who don`t speaks English but that want to be better.
Estoy tratando de hacer que funcione pero se queda mucho tiempo "pensando" y después del segundo o tercer intento ya no "piensa".
No se muestra bien en Opera :´-(
Pero el de la página:
http://www.brandspankingnew.net/specials/ajax_autosuggest/ajax_autosuggest_autocomplete.html
sí se ve bien.
La línea:
var json=new AutoComplete('test_json',options)
genera un error en el IE al hacer clic en el campo de escribir cuando no hay resultados luego de varios intentos. Y en Opera no se ven los resultados.
Quisiera ver un Demo publicado de este sistema para comparar con el que traté de hacer funcionar.
Gracias.
anonimo:
siento mucho lo del problema de IE, yo tengo implmentado el autocomplete en el proyecto donde actualmente trabajo y tuve que cambiar la creacion del objeto a otra forma. En la aplicación implementé la creación de un autocomplete en una función que formaba parte de un objeto:
registerAutoComplete: function(id){
var me = this;
var options = {
script: me.JSP_SERVER+'webmail/autocomplete.cl?json=true&limit=6&',
varname:'input',
json:true,
shownoresults:false,
maxresults:16,
callback: null
};
var json=new AutoComplete(id,options);
},
para usarla, solo he de llamarla a través del objeto y darle el identificador del campo de texto a convertir:
OBJETO.registerAutocomplete('ID');
y la verdad que no he tenido problemas aún...
Saludos
Doctype Issue
Someone stated before that Doctype leads to problems for this script. I had the same issue too. I removed the doctype and it worked.
Releasing Enter Key to submit form
I made a minor modification on the script. It was not letting the user to submit the form with enter key even though there was no auto complete option visible.
Search for "Release Enter Key Edit" in the code you will see the modifications. -> acgmail.js
Thanks for your great work by the way :)
Tony, este autocomplete esta espectacular, aunque tiene un problema que aun no logro solucionar.
Mira, luego de usar el autocomplete, (clickear alguno de la lista), y luego presionar un boton, un link, o cualquier objeto que haga perder el foco, la lista posteriormente no se mostrara.
Voy a quitar la opcion de cerrar la lista al sacar el mouse y cambiarlo por una opcion que sea "nula".
I seem to have a problem with getting the data from a database...If i populate the arrays from a db the script doesnt work, although the data are correct. Can you post a working db example ?
hola tony.. mira, en IE6 tiene 2 problemitas de CSS:
1º) el efecto de redondeado de la parte superior de un elemento seleccionado se ven fuera de su lugar. en las siguientes clases:
- div.autocomplete ul li.ac_highlight a .tl
- div.autocomplete ul li.ac_highlight a .tr
tienen la propiedad background-position: bottom en ambas clases, cuando deberian ser top. yo corregi estos valores y se ve perfecto!
el otro detalle que tiene.
cuando tenes un estilo global para los links supongamos
a:hover {
text-decoration: underline;
}
los links de la lista tambien heredan esta propiedad y soy sincero... queda horrible :P
asi que en la clase
div.autocomplete ul li a:hover
coloque text-decoration:none;
lo demas funciona todo excelente!
me ha sido muy util tu clase :)
Gracias!
muchisimas gracias martin
otra cosita Tony, el tema de los eventos de las teclas:
1º cuando el elemento autocomplete esta visible el comportamiento de las teclas es el siguiente:
enter: selecciona item y coloca el texto en el input
tab: == enter
up y down: up y down :P
pero! cuando el elemnto esta no esta activo (visible) las teclas no deberian comportarse de igual manera.
supongamos que el input es para insertar una cadena de busqueda, y ninguna de las opciones que me "sugirio" el script me agrada y quiero buscar con el texto que yo ingrese, al presionar "Enter" el campo toma el valor del ultimo item del autocomplete y ahi recien hace submit del form. eso esta mal.
otro ejemplo, yo complete el campo a gusto (utilizando o no alguna sugerencia del script) y quiero pasar a otro, al presionar TAB, sucede lo mismo que si presiono enter, ¡opa! pero si yo queria pasar al otro campo! esto tambien esta mal :P
para solucionar esto hice lo siguiente:
defini una variable mas, llamada "visible" en las "Init variables"
this.visible = false
en la funcion onKeyPress encerre el switch(key) en un
if (this.visible) {
switch(key)
{.......}
}
en la funcion createlist
agregue despues de document.getElementsByTagName("body")[0].appendChild(div);
lo siguiente:
this.visible = true;
y en la funcion clearSuggestions
despues de $(this.acID).remove();
agregue
this.visible = false;
haciendo esto cuando el elemento esta visible las teclas funcionen como nosotros queremos. Y cuando no este visible funcionen con normalidad.
Salu2!
Hi Tony,
First off, Kudos to you and Tim for sharing such excellent work with all of us.
There's a few things, that I would like to, but unable to get it working:
1. Invoke another PHP script, when a value is selected from the "suggested" drop down.
For example:
If a person's Name is selected, then send the person's userid to another script as such:
getUserDetails.php?input='userid'
2. I would like to narrow down suggestions by FirstName and LastName.
For example, the Input would be:
james,matthew
I'd appreciate your help with the above issues.
Thanks,
Matt
Hi there anonymous... how are you doing? Hope I can help you:
1)Have you checked the onchange event of the input field? that could fire the php script easily, whether by .location.href or via ajax.
2)Could you be more specific? Suggestions are set on the PHP file... and i have used an array as an example but that could be easily changed to extract suggestions from a database. Then it is here:
{\"id\": \"".$aResults[$i]['id']."\", \"value\": \"".$aResults[$i]['value']."\", \"info\":\"".$aResults[$i]['info']."\"}"
Where you need to change the values in the format you want them to be displayed...
Hope it helps
Hi Tony,
I am doing good....thank you.
I hope everything's great with you.
Thanks a lot for your quick response.
1. I was using an onchange event, but wasn't using it correctly.For some reason, "onchange" wasn't working directly on the input fields.
So,I made the changes to callback() as such: ( The callback function is invoking a function called getUserData,which is part of another AJAX script.)
callback: function (obj) { document.getElementById('clID').value=obj.id;
document.getElementById('clID').focus();
document.getElementById('clID').onfocus = getUserData;
}
It works like MAGIC... ;-)
2. I wanted the user to enter a Full Name like ' ton span ' and the search alogrithm should interpret the delimited string
as FN = ton% and LN = span%.
I have a database, wherein there could be atleast 1000 "smiths", and I wanted to narrow down the "Suggested" results.
So, I used the PHP 'explode' function to split the input string.
$input = strtolower( $_GET['input'] );
$len = strlen($input);
$parts = explode(" ", $input);
$fn = $parts[0];
$ln = $parts[1];
and then, ofcourse, pass the variables to a SQL query ( Bingo !... :-)
Once again, thanks for the excellent scripts, Sir.
Greetings,
Matt.
Hi,
There is a SELECT listbox just below the "Auto Suggest" text box in my form.
When the dropdown suggested results show up, the SELECT listbox field is overlapping ( rather cutting out) a part of the "suggested" results.
Can you please suggest a workaround for this issue.
Thanks in advance.
Greetings,
Matt.
Hi Anonymous... the best way is to create an IFRAME with the same measurements as the DIV holding the suggestions... this IFRAME should be inserted within the dimensions of the DIV and put its visibility CSS attribute to 0. This should work on all IE (thank you mr Gates! - you moved from overflow 6 to silly browser!)
Hope it helps
Hi Tony,
Thanks for such a quick response.
I tried using iframe within a div, but it didn't work. ( I am quite sure that I am not writing it correctly )
So, I just set/unset the visibility of the SELECT element
via JS. This helped solve the issue.
I appreciate all your help.
Greetings,
Matt.
Hi Tony,
I have another question.Sorry, I am asking too many questions.... ;-)
We are using IE 6 and the TAB key is not triggering the "auto-complete" script.
In order to enable the user to enter many characters in the input field, the minchars was set to 15 in the OPTIONS.
How do I prevent an auto-triggering of the script? If the user enters 15 chars, then the script should be executed only on a TAB event.
Appreciate your help.
Thanks,
Matt.
Saludos, he descargado el paquete y me parece genial, pero al probarlo con ie6 he encontrado un inconveniente con las esquinas en el resaltado de los resultados, no encajan bien en las eskinas y se ve mal, alguna sugerencia ? se los agradeceria mucho.
dafevara at gmail dot com
Hola Tony,
hope you will find some time to help me figure that out.
I'm trying to achieve a suggestion list with categories. By categories I mean some text above the suggestions, eg. when I type "c" it should display
food (category)
- cake (sugg)
- carrot (sugg)
drinks (category)
- cocktail (sugg)
- cachaca (sugg)
So far it's working like this, the problem is that I don't want to highlight categories and by going up/down with keyboard simply avoid it. I've changed the changeHighlight function to this:
changeHighlight: function(key) { // {{{
var list = $("ac_ul");
if (!list)
return false;
var str = this.getLastInput(this.fld.value);
str = this.aSug[ this.iHigh -1 ].id;
var n;
if(key == Event.KEY_DOWN || key == Event.KEY_TAB){
n = (str == "0") ? this.iHigh + 2 : this.iHigh + 1;
} else {
n = (str == "0") ? this.iHigh - 2 : this.iHigh - 1;
}
n = (n > list.childNodes.length)? list.childNodes.length : ((n < 1)? 1 : n);
this.setHighlight(n);
},
after this I can't navigate to categories - which is what I wanted. The problem is with highlighting, I'll try to explain it to you on simple use case on the suggestion tree that I wrote above: I navigated with keydowns to the "carrot", then I press keydown and it navigates to cocktail (ommiting category drink) but doesn't highlight, then I press keydown and it navigates to cachaca and it's highlighted. The same thing happens when I go up. I hope this is understandable, if not please let me know and I will provide more info.
I'm using ff3 but it's the same with ff2.
Best regards,
Bartosz
thanks for this excellent script. is it possible to submit another value from the form - for example someone types a name and i only need the ID from the database (because the name is not unique)?
can anyone tell me how to do this? im really bad at js since im more the php/mysql guy.
so far i have a hidden input field 'user_id' after span id='xml_info', and my ID is in "obj.id". how can i copy obj.id to user_id.value via js?
Hola buenos dias... Tengo un problema con el script del autocomplete.. funciona bien en plataforma windows, en xampp y en todos los navegadores pero cuando lo paso al servidor linux Ubuntu y no me hace absolutamente nada... Alguien mas a tenido este problema, si es asi por favor necesito ayuda...
Gracias
Carpool Guy:
You must change (in test.html) on line 141:
callback: function (obj) { $('json_info').update('you have selected: '+obj.id + ' ' + obj.value + ' (' + obj.info + ')'); }
to:
callback: function (obj) { $('your_hidden_input').value=obj.id}
This will put obj.id value on 'your_hidden_input' element so you can use it on Get or Post later.
I hope to help you. (Sorry for my poor english)
Hola Tony,
hay un pequeño problema en autocomplete.css y en el script con respecto a el resaltado de la opción shownoresults:
Cuando intentas asignar la clase que le corresponde al elemento li de shownoresults (línea 358):
var li = this.createDOMElement('li', {className: 'ac_warning'}, this.options.noresults );
le asignas la clase ac_warning, que en el autocomplete.css aparece como as_warning.
Cambié as_warning por ac_warning en el css.
Por sí solo no funcionará, ya que en la línea 451 llamas a this.setHighlight(1), sustituyendo la clase por ac_highlight erróneamente (a mi pensar), aunque no exista ningún resultado válido. También al presionar flecha abajo/arriba se cambia la clase, asi que cambié la función setHighlight (línea 476) a:
setHighlight: function(n) { // {{{
if (!(this.aSug.length == 0 && this.options.shownoresults)){
var list = $('ac_ul');
if (!list) return false;
if (this.iHigh > 0) this.clearHighlight();
this.iHigh = Number(n);
list.childNodes[this.iHigh-1].className = 'ac_highlight';
this.killTimeout();
}
}, // }}}
para resaltar sólo si hay resultados en cualquier llamada que se le haga.
He notado Tony que hay cambios que al parecer has incorporado al ZIP y otros no, por ejemplo el cambio del problema en IE6 donde el efecto de redondeado de la parte superior de un elemento seleccionado está movido de su lugar, que sugirió martin el 21 de abril de 2008 está correcto y no viene en el paquete, a todos nos gustaría que los incluyeras.
Muchísimas gracias por tu excelente trabajo, seguro que le haz ahorrado tiempo a muchos incluyéndome y perdona por el post tan largo.
Tienes toda la razón, tengo todo el script pero no he tenido tiempo de nada debido a mi trabajo actual.
En cuanto pueda, actualizaré el ZIP, espero hacerlo durante este fin de semana.
Un abrazo y gracias por utilizar el script
Hi Tony
This is a great script and thanks for sharing. I notice the maxheight option isn't working. Is this a leftover from previous versions, or is it supposed to work? Could you please answer me directly through email?
Thanks!
Tommy
Hi,
When fetching the records from database,displaying the data to suggest take long time why????????
I need the data suddenly display.
pls any one can help me
Hello,
Try setting an index on the field that you are looking up. ( the index will definitely speed retrieval )
Hope that helps.
I've got AutoComplete up and running, but in IE6, the 2 select boxes that I have beneath the search field are showing through the results list...I tried setting the z-index to a higher number (10), but didn't have any luck. Any suggestions?
Hello,
A Post had been opened for this on May 27th.
Please look for that thread.
HI,
It has some unexpected error:
I always recive the same error message (JS alert):
?????????????????????????????
"AJAX error: [object Object]"
?????????????????????????????
Why??? I'm using your version 1.0.3, prototype 1.6.0.0 and JSON.
Please give me a hint!
I discovered a inconsistencs of the object: maxresult != maxentries, but what should one use?
fantastic tool. will be implementing this soon!
PERFECTO!!! EXCELENTE!!
PERFECT!! EXELENT!!
Take a look here http://www.facildesubir.com/
Hi, Tony
Great script, I want to use it with my dictionary, but I have problem with Polish characters - when I write Polish characters in test.php everything is OK, but when they come from mysql they are displayed incorrectly. You wrote in test.php a comment:
//had to use utf_decode, here
// not necessary if the results are coming from mysql
How to make utf_decode not necessary?
Any help will be apreciated.
This script is awesome and is working like a dream for me in IE7. For some reason I can't get the styling to work for Firefox. It just throws everything, un-styled, left-aligned at the bottom of the page.
Hi, seems that the download zip only contains the .js file, no styles or images?
hey el .zip solo trae el archivo .js como se supone que debo insertar eso en mi wordpress ?
no encuentro ninguna instrucciones :(
sera que me podrian ayudar ?
gracias totales :)
APOLOGIES
Sorry for those who downloaded only the updated file .js, I uploaded now the right zip file...
Hi,
the script has a problem with IE (6 and 7), FF works perfectly. The "test.html" produces the following js-error:
Object doesn't support this action
test.html Line: 143
The line 143 is:
var json=new AutoComplete('test_json',options);return true;" value="" />
Can somebody help me?
Best reguards
I am attempting to use gson to generate json to be sent back to the client. The client is making an AJAX call and is using the
AutoComplete js lib.
When I send the JSON back to the client the json looks like this:
{ results: [
{"id":"55031","value":"Douglas","info":"016"}
{"id":"55027","value":"Dodge","info":"014"}
{"id":"55029","value":"Door","info":"015"}
{"id":"55025","value":"Dane","info":"013"}
{"id":"55033","value":"Dunn","info":"017"}
]}
The AutoComplete JS lib can't deal with the field name quotes. When I change the server side to return a hard-coded value like this the
AutoComplete works.
{ results: [
{ id: "1", value: "Foobar", info: "Cheshire" },
{ id: "2", value: "Foobarfly", info: "Shropshire" },
{ id: "3", value: "Foobarnacle", info: "Essex" }
]}
Any ideas on how to fix this, while still leveraging server-side JSON tools?
Thanks.
Hi JB,
The problem you have is quite easy: YOU ARE NOT USING JSON notation. The brackets {} means you are sending an object, where id:"value", id is a property and value its value... You MUST in order to use JSON notation to follow its rules...
Regards
I ran the code below through a JSON validator and I finally got it to accept it when it looked like the new version below. I also checked the use of "" on field names and as far as I can tell that seems to be ok too. So, I thought the code below would be OK.
[
{"id":"55031","value":"Douglas","info":"016"},
{"id":"55027","value":"Dodge","info":"014"},
{"id":"55029","value":"Door","info":"015"},
{"id":"55025","value":"Dane","info":"013"},
{"id":"55033","value":"Dunn","info":"017"}
]
But, AutoComplete does not seem to handle it.
Here that? That's me slamming my palm into my forehead.
I figured it out, my bad. The problem was not the quotes around the field names it was at the root level. I forgot to double quote the results: field. This is what is being sent back now and it works!
{ "results": [
{"id":"55017","value":"Chippewa","info":"009"},
{"id":"55015","value":"Calumet","info":"008"},
{"id":"55021","value":"Columbia","info":"011"},
{"id":"55019","value":"Clark","info":"010"},
{"id":"55023","value":"Crawford","info":"012"}]}
Thanks Tony and all contributors. Nice component!
JB
I create a new class base on your autocomplete.js. This one is look like Facebook auto-suggest field friend.
Here the demo: http://code.lokamaya.net/autofield/autofield.php
I also modify the trap for keystroke:UP,DOWN,HOME,END. And create an auto-scroling or auto-focus the DIV when interact with that keys.
autotext field demo
Hi Tony,
On May 27, 2008, Anonymous asked you a question with regards to the select boxes interfering with the autocomplete in IE6. Can you tell me in what function or where exactly to put the iframe codes to fix this? Or can someone post a code example?
Thanks.
Anyway to make this faster to start off with at all? It seems there is quite a bit of delay in getting the initial results back (compared to say, the jquery autocomplete).
I noticed a comment up above that said "Try setting an index on the field that you are looking up. ( the index will definitely speed retrieval "
However, I am not sure what they mean by this. Could someone respond and provide some suggestions for speeding this up? Thanks!
Hello,
Is there a way to set the initial list of selected values?
Thanks,
Levy
I noticed that the Spinner does not change back to the magnifying glass.
Is this by design?
The browser in question is IE7, obviously I have the usenotifier option set to true.
Steve
is there any way to change the lower case characters in upper case and vice verse using html
IT Solution
The zip file does not seem available to download. Is this still accessible?
hi ,
the download link is not working.
Please can you correct the link?
Thanks
Anyone have this script using Jquery? I already use this with prototype, but now I need to convert to Jquery, Do you have?
Hi,
Fantastic! very nice.
Would you be able to have option with radio button?
I want to have two radio button and want to make auto suggestions depends on radio button selection. I could not find any solutions for this and hopefully you will be able to help.
Thanks!
Jung
The link is dead anyone have mirror?
gr8ly thanks
Who knows where to download XRumer 5.0 Palladium?
Help, please. All recommend this program to effectively advertise on the Internet, this is the best program!
The link to /tmp/ on the download above is broken.
The zip file can also be found on softpedia. Here:
http://webscripts.softpedia.com/script/Form-Processors/Ajax-powered-auto-complete-44161.html
Thanks, were in the search of this tool autocomplete for my Web.
Post a Comment