public
Created

  • Download Gist
autocomplete
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
// jQuery Autocomplete javascript
 
// This is my working autocomplete js.
$(function() {
$('#select_origin').autocomplete({
minLength: 2,
source: '/people.json',
focus: function(event, ui) {
$('#select_origin').val(ui.item.person.given_name);
return false;
},
select: function(event, ui) {
$('#select_origin').val(ui.item.person.given_name);
$('#link_origin_id').val(ui.item.person.id);
return false;
}
})
.data( "autocomplete" )._renderItem = function( ul, item ) {
return $( "<li></li>" )
.data( "item.autocomplete", item )
.append( "<a>" + item.person.given_name + "</a>" )
.appendTo( ul );
};
});
 
 
 
//This is my new autocomplete using 'live" as jim suggests:
 
// jQuery Autocomplete javascript
 
// origin_person selector
$(function() {
$('#select_origin').live('autocomplete', {
minLength: 2,
source: '/people.json',
focus: function(event, ui) {
$('#select_origin').val(ui.item.person.given_name);
return false;
},
select: function(event, ui) {
$('#select_origin').val(ui.item.person.given_name);
$('#link_origin_id').val(ui.item.person.id);
return false;
}
})
.data( "autocomplete" )._renderItem = function( ul, item ) {
return $( "<li></li>" )
.data( "item.autocomplete", item )
.append( "<a>" + item.person.given_name + "</a>" )
.appendTo( ul );
};
})
 
 
//Using the "live" function, firebug gives me the following error:
 
$("#select_origin").live("autocomplete", {minLength: 2, source: "/people.json", focus: function (event, ui) {$("#select_origin").val(ui.item.person.given_name);return false;}, select: function (event, ui) {$("#select_origin").val(ui.item.person.given_name);$("#link_origin_id").val(ui.item.person.id);return false;}}).data("autocomplete") is undefined
http://localhost:3000/javascripts/application.js?1279868823
Line 54

Okay just worked out how to use the live() event. Also code is refactored so that it can be used for multiple textfields with out huge duplication.

//person selector function

$.fn.person_autocomplete = function(hidden_field) {
$(this).autocomplete({
minLength: 2,
source: '/people.json',
focus: function(event, ui) {
$(this).val(ui.item.person.given_name);
return false;
},
select: function(event, ui) {
$(this).val(ui.item.person.given_name);
hidden_field.val(ui.item.person.id);
return false;
}
})
.data( "autocomplete" )._renderItem = function( ul, item ) {
return $( "

" )
.data( "item.autocomplete", item )
.append( "" + item.person.given_name + "" )
.appendTo( ul );
}
}

// define fields here using hidden field in view.
$('input').live('focus', function() {
if (!$(this).hasClass('ui-autocomplete-input')) {
$(this).person_autocomplete($('#link_origin_id'))
}
})

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.