

En días pasados tuve la necesidad de crear una interfaz web para redacción, donde a partir de un textbox y lo que ellos iban escribiendo, se hacia una consulta a la Base de Datos y les desplegaba unos terminos que contenian el texto hasta ese momento ingresado, para esto utilice jquery y jquery-ui (User Interface), realmente fue muy sencillo y a continuación les muestro los pasos necesarios.
Lo primero que debemos hacer es descargar las librerias de jquery-ui que nos permitirán usar la funcionalidad de autocompletar:
Aqui ya tenemos las librerias necesarias para hacer nuestro autocompletar por medio de javascript.
Ahora creamos una página html cualquiera y la modificamos para incluir las librerias js y css antes descargadas, puede ser en el head o en el body del documento html:
<script src="../jquery/js/jquery-1.4.2.min.js" type="text/javascript"></script> <script src="../jquery/js/jquery-ui-1.8.4.custom.min.js" type="text/javascript"></script>
Vamos a crear un textbox con id “palabra” que será el que utilizaremos para hacer el llamado al autocompletar, y dos campos de tipo oculto donde vamos a almacenar el id y el valor de la palabra que seleccionemos:
<input id="palabra" size="30" value='' > <input type='hidden' id='palabraId' value='' > <input type='hidden' id='palabraTexto' value='' >
Creamos la función que se va a encargar de hacer el llamado al script que trae las posibles opciones a partir del texto ingresado en el textbox:
<script type="text/javascript"> $(function() { //Se encarga de ejecutar la función autocomplete de jqueryui $("#palabra").autocomplete({ source: function(request, response) { //Llamado al script Search.php que devuelve arreglo JSON $.getJSON("/Search.php", { term: request.term }, response); }, minLength: 2, //Numero de caracteres minimos //Cuando el usuario selecciona una opción asigna los valores a los campos ocultos select: function(event, ui) { $("#palabraId").val(ui.item.id); $("#palabraTexto").val(ui.item.value); }, }) //Función que se encarga de desplegar las opciones .data( "autocomplete" )._renderItem = function( ul, item ) { return $( "<li></li>" ) .data( "item.autocomplete", item ) .append( "<a>" + item.value + "</a>" ) .appendTo( ul ); }; }); </script>
<style> //Asignamos un gif para mostrarle al cliente que se estan buscando opciones .ui-autocomplete-loading { background: url(../jquery/css/images/indicator.gif) no-repeat right; } #palabra{ width: 15em; } </style>
El script Search.php debe devolver un arreglo de tipo JSON con las columnas “id” y “value” para que sean desplegadas como opciones en el textbox, aca les dejo un ejemplo de respuesta:
[{"id":711,"value":"Columnistas","total":0},{"id":600,"value":"Econom\u00eda","total":0},{"id":510,"value":"F\u00fatbol Colombiano","total":0},{"id":100,"value":"Colombia","total":14},{"id":810,"value":"Telecomunicaciones","total":0},{"id":814,"value":"Consejos","total":0},{"id":1113,"value":"Ecolog\u00eda","total":0},{"id":1548,"value":"contenido","total":1},{"id":1562,"value":"Atl\u00e1ntico","total":4},{"id":1572,"value":"Puerto Colombia","total":1},{"id":1576,"value":"Centro de Convenciones","total":3}]
Esta es una imagen de como se veria el textbox en el momento en que se escriben dos caracteres:
despues en el momento de navegar con las flechas por las posibles opciones:
En siguientes entradas les mostrare como acceder con jquery a las estructuras html, adicionar, modificar y eliminar entidades HTML.
Tags: ajax, autocompletar, autocomplete, javascript, jquery, jqueryui, tags, textbox














Please, can you PM me and tell me few more thinks about this, I am really fan of your blog…
With thanks for this great post. Have been bored in function all day until eventually I stumbled across this submit, truly received me thinking about some stuff
What youre saying is completely true. I know that everybody must say the same thing, but I just think that you put it in a way that everyone can understand. I also love the images you put in here. They fit so well with what youre trying to say. Im sure youll reach so many people with what youve got to say.
This is a smart blog. I mean it. You have so much knowledge about this issue, and so much passion. You also know how to make people rally behind it, obviously from the responses. Youve got a design here thats not too flashy, but makes a statement as big as what youre saying. Great job, indeed.
Thank you for yet another good post. I’ve a presentation next few days, and I will be on the look out for this type of information.
Thankful i recently uncovered this excellent website, Another good site is Dbol will be sure to save it so i can browse frequently.
Thankful i ran across this site, will be sure to save it, Another good site is Dbol so i can pay a visit to frequently.
Adding to my bookmarks thanks, a good quick read.
Delighted i discovered , this excellent website, Another good site is Dbol will be sure to bookmark it so i can drop by frequently.
Have you ever considered adding more videos to your blog posts to keep the readers more entertained? I mean I just read through the entire article of yours and it was quite good but since I’m more of a visual learner,I found that to be more helpful well let me know how it turns out! I love what you guys are always up too. Such clever work and reporting! Keep up the great works guys I’ve added you guys to my blogroll. This is a great article thanks for sharing this informative information.. I will visit your blog regularly for some latest post.
makeup brushes is good is excellent
This is a great web page, would you be interested in doing an interview about just how you designed it? If so e-mail me!
Have you considered about introducing some social bookmarking buttons to these blogs. At least for twitter.
Great post! I?m just starting out in community management/marketing media and trying to learn how to do it well – resources like this article are incredibly helpful. As our company is based in the US, it?s all a bit new to us. The example above is something that I worry about as well, how to show your own genuine enthusiasm and share the fact that your product is useful in that case
I just added this blog site to my google reader, great stuff. Cannot get enough!
Very attention grabbing post – might be outdated, but it was new to me. I wished say thanks for this good article Jquery – AutoCompletar | Infraestructura y Servicios! I definitely enjoyed reading each bit of it. I have you bookmarked to check out new stuff you publish.
I appreciate your wp web template, exactly where did you get a hold of it through?
I have been checking your blog for a although now, would seem like daily I understand one thing new Thanks
Couldn?t be written any better. Reading this post reminds me of my old room mate! He always kept talking about this. I will forward this article to him. Pretty sure he will have a good read. Thanks for sharing! wajadud555
This is a excellent web page, could you be interested in doing an interview regarding how you designed it? If so e-mail me!
I tried to publish a comment previously, yet it has not shown up. I think your spam filter may be broken?
Once I came over to this post I can only see part of it, is this my net web browser or the internet web site? Should I restart?
Very attention grabbing post – is perhaps outdated, but it was new to me. I wanted say thanks for this nice article Jquery – AutoCompletar | Infraestructura y Servicios! I definitely loved reading each little bit of it. I have you bookmarked to take a look at new articles you write.
Nice site, nice and easy on the eyes and great content too.
What a great site and informative posts, I will add backlink – bookmark this site?
thanks !! very helpful post!
What you said made a lot of sense. But, think about this, what if you added a little content? I mean, I dont want to tell you how to run your blog, but what if you added something to maybe get peoples attention? Just like a video or a picture or two to get people excited about what youve got to say. In my opinion, it would make your blog come to life a little bit.
Terrific read! I have one advice for your webpage. It seems like there are some css issues when opening several pages in google chrome and safari. It is functioning fine in internet explorer. Probably you can double check that. I’ve just book marked this article on digg.com to acquire a few more readers to your web page.
Es una buena opción para un diccionario de terminos no muy grande, en el autocompletar de jquery existe la opción tambien de que la fuente sea un arreglo javascript que se aloja en memoria, o usted podria tambien tener un archivo aparte .js donde define el arreglo con todos sus elementos y lo llama desde la funcion principal del autocompletar, asi puede manejar cache a diferentes niveles en el mismo, y tambien para la busqueda se encarga jqueryui.
El problema que le vi es que puede llegar a ser muy grande ese archivo, no se tiene certeza de cuantas palabras se van a tener, en mi opinion superan los 100.000 que usted menciona. De todas maneras en la consulta a la Bd se manejan caches intermedios como lo es el memcached.
Sin embargo es otra alternativa para lograr el mismo resultado, al final depende del gusto del consumidor, pero gracias por su aporte le echare un vistazo.
vea pues… yo hice lo mismo en mi anterior trabajo usando TextboxList (http://devthought.com/projects/jquery/textboxlist/).
Para implementar ese ‘Search.php’, creé un arreglo (que se mantenía en caché) que contenía todos los tags posibles, y se hacía una búsqueda binaria (proveída por el plugin de TextboxList) para el autocompletar. Para una cantidad menor a 100.000 tags (mas o menos unas 15 veces el número de tags existentes hasta ese momento) se comportaba bastante bien.
Qué opina? de pronto le eliminaría la necesidad de consultar a la base de datos para autocompletar cada tag.