Skip to content

Instantly share code, notes, and snippets.

@etozzato
Created July 18, 2011 08:50
Show Gist options
  • Select an option

  • Save etozzato/1088932 to your computer and use it in GitHub Desktop.

Select an option

Save etozzato/1088932 to your computer and use it in GitHub Desktop.
$(document).ready(function() {
autocomplete_fields()
});
function autocomplete_fields(){
$('input.autocomplete').each(function(){
// lost focus: hide suggestions and select current option
$(this).focusout(function(){
hide_and_complete(this);
return false;
});
// mouse up: hide suggestion and select current option
$(this).mouseup(function(){
hide_and_complete(this);
return false;
});
// keypress is only used for the return key
$(this).keypress(function(event){
if (event.keyCode==13){
hide_and_complete(this);
return false;
}
});
$(this).keyup(function(event){
if(event.keyCode==38){
var index = find_index('div.autocomplete ul li');
if (--index < 0){ index = options_count(this)-1}
$(autocomplete_id(this) + '_' + (index)).addClass('selected').siblings().removeClass('selected')
}
if (event.keyCode==40){
var index = find_index('div.autocomplete ul li');
if (++index >= options_count(this)){ index = 0; }
$(autocomplete_id(this) + '_' + (index)).addClass('selected').siblings().removeClass('selected')
}
// letters, numbers and backspace trigger the autocomplete search
if ($(this).val().length >= 2 && ((event.keyCode>45 && event.keyCode<106) || event.keyCode==8)){
$.get(autocomplete_url(this), null, null, "script");
}
return false;
});
});
}
function find_index(el){
var str = $('li.selected');
return $(el).index(str);
}
function hide_and_complete(el){
$(el).val($(autocomplete_id(el) + ' .selected').html());
$(autocomplete_id(el)).hide();
}
function autocomplete_id(el){
return '#' + $(el).attr('klass') + '_' + $(el).attr('method') + '_autocomplete'
}
function autocomplete_url(el){
return '/autocomplete/' + $(el).attr('klass') + '/' + $(el).attr('method') + '/' + $(el).val()
}
function options_count(el){
return $(autocomplete_id(el) + ' ul li').size()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment