Skip to content

@dpasley /autocomplete
Created

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
// 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
@dpasley
Owner

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'))
    }
    })

  • Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
    Something went wrong with that request. Please try again.