/** * Plugin : Autocompletar con jQuery * Autor : Lucas Forchino * WebSite : http://www.tutorialjquery.com * version : 1.0 * Licencia: Pueden usar libremenete este código siempre y cuando no sea para * publicarlo como ejemplo de autocompletar en otro sitio. */ (function($){ //Variable to represent the ajax that query the data. var objXmlHttp; //Variable to control the deleted of the suggestion list when the user click out the input field. var deleteSuggestionList = true; // Creo la funcion en el prototype de jQuery de manera de integrarla $.fn.autocomplete= function () { //puede haber mas de un autocomplete que cargar por eso esto los levanta a todos $(this).each(function(){ // aplico los estilos a los elementos elegidos $(this).addClass('autocomplete-jquery-aBox'); //Variable to know the name of the field (input) that receive the data. var nameInput = ''; // guardo en una variable una nueva funcion que asigna el texto del // link que paso en that al input donde escribimos. // esto seleccionaria el link del cuadro autocompletar var selectItem = function(that) { // partiendo del link busco el input y le asigno el valor del link $(that).parent().parent().find('input').val($(that).html()); nameInput = $(that).parent().parent().find('input').attr('name'); // remuevo el cuadro de autocompletar, se supone si ya seleccionaste // un valor no se necesita mas $(that).parent().remove(); //Check which field has received the info and execute the method that handled the field value. switch(nameInput) { case 'newCategory': showNewCategory(); break; case 'newLocation': newLocation(); break; } //Make available the variable "deleteSuggestionList" for the next cycle. deleteSuggestionList = true; } //Search the input and assign an event when a key is pressed. $(this).find('input').bind('keypress',function(theEvent){ var input=$(this); var newEvent = theEvent || window.event; code = newEvent.charCode || newEvent.keyCode; // si es Enter => seleccionar el link marcado if (code==13 && $('.autocomplete-jquery-mark').size()>0) { var element=$('.autocomplete-jquery-mark').get(0); selectItem(element); } //If is the key execute the method that handled the field value. if (code==13) { //Take the name of the input field and execute the method that handled the field value. nameInput = $(this).attr('name') $(this).val($(this).val().trim()); //To delete the space before the name of the category. switch(nameInput) { case 'newCategory': showNewCategory(); break; case 'newLocation': newLocation(); break; } } //If is the scape key clear the autocomplete box if (code == 27 || code == 13) { input.parent().find('.autocomplete-jquery-results').remove(); } // si son las flechas => moverse por los links else if(code==40 || code ==38) { elements =$('.autocomplete-jquery-results').find('a'); var mark =0; if ($('.autocomplete-jquery-mark').size()>0){ mark=$('.autocomplete-jquery-mark').attr('data-id'); $('.autocomplete-jquery-mark').removeClass('autocomplete-jquery-mark'); if (code==38){ mark --; }else{ mark ++; } if (mark > elements.size()){ mark=0; }else if (mark < 0){ mark=elements.size(); } } elements.each(function(){ if ($(this).attr('data-id')==mark) { $(this).addClass('autocomplete-jquery-mark'); } }); } // si es una letra o caracter, ejecutar el autocompletar // con este filtro solo toma caracteres para la busqueda else if((code>47 && code<91)||(code>96 && code<123) || (code>127 && code<166) || (code > 34 && code < 37)|| code ==8 || code == 173 || code == 196 || code == 214 || code == 220 || code == 228 || code == 246 || code == 252) { if (input.val().length == 0 && code == 8) { return; } if (objXmlHttp) { objXmlHttp.abort(); } // si presiono me fijo si hay resultados para lo que tengo // tomo la url var url = input.attr('data-source'); //Take the value of the field input and add the character that the user have pressed. var value = escape(strip(input.val().trim())); if (value!='undefined') { value += escape(String.fromCharCode(code)) } else { value = ''; value = escape(String.fromCharCode(code)); } url+=value; //busco en el server la info objXmlHttp = $.getJSON(url,{}, function(data){ // si encontro algo // creo un cuadro debajo del input con los resultados input.parent().find('.autocomplete-jquery-results').remove(); var left = input.position().left; var width= input.width(); var result=$('
'); // le damos algunos estilos al combo result.css({'width':width}); result.css({'left':left}); result.addClass('autocomplete-jquery-results'); //Make on or off the variable "deleteSuggestionList" when the user go in or out the division. //This variable is used to know if the user make click over the sugestion list. result.mouseover (function (){ deleteSuggestionList = false; }) result.mouseout (function (){ deleteSuggestionList = true; }) for(index in data) { //agrego un link por resultado if(data.hasOwnProperty(index)) { var a = $(''); a.html(data[index]); a.addClass('autocomplete-jquery-item'); var widthFixed=width - 3; a.css({'width':widthFixed}); a.attr('href',"#"); a.click(function (){ // funcion que pone el texto en input selectItem(this); }) a.attr('data-id',index); $(result).append(a); } } if (data.length>0) { input.parent().append(result); result.fadeIn('slow'); } }); } $(input).bind('blur',function(event){ if (deleteSuggestionList == true) { input.parent().find('.autocomplete-jquery-results').remove(); } }); }); }); } })(jQuery);