mburesh
mburesh

Reputation: 1028

jQuery Autocomplete input clears itself

I am using jQuery Autocomplete in a WordPress custom post. When filling out the autocomplete input field, the ajax seems to work correctly, and returns matching data. Once I select an item in the drop-down list though, the input field clears itself. I walked through the JavaScript step by step, and the input field #title is correctly set by the populateForm() function but at some point after my script has finished, the field is emptied.

Does anyone know what might be causing this, or of a decent way I could work around it?

I've included my js below. Let me know if there's any other information that might help.

(function ($) {
var url = ajax_object.ajaxurl;
var popped = []

$('#title')
        .autocomplete({
            source: function( request, response ) {
            $.getJSON( url, {
                term : extractLast( request.term ),
                action : 'autocomplete'
            }, response);
        },
        search: function() {
            var term = extractLast( this.value );
            if ( term.length < 2 ) {
                return false;
            }
        },
        select: function( event, ui ) {
            populateForm(ui.item);
        },
        response: function( event, ui ) { 
            for (var i in ui.content) {
                popped.push(ui.content[i]);
            }
        }
    }).data("ui-autocomplete")._renderItem = function(ul, item) {
            return $("<li></li>")
                .data("ui-autocomplete-item", item)
                .append("<a><strong>" + item.name + "</strong> (" + item.username.replace(/[^a-zA-Z]+/g, '') + ")</a>")
                .appendTo(ul);
    };

function populateForm(obj) {
    $('input#title').val(obj['username']);
    for (var property in obj) {
        if (obj.hasOwnProperty(property)) {
            $('input#form-' + property).val(obj[property]);
        }
    }
}

function split( val ) {
    return val.split( /,\s*/ );
}

function extractLast( term ) {
    return split( term ).pop();
}
})(jQuery);

Upvotes: 0

Views: 151

Answers (1)

Rodney G
Rodney G

Reputation: 4826

Per the Autocomplete docs, the select event's ui.item has only 2 properties: label and value. You are passing it to populateForm() and then trying to change your text input's value to ui.item.username. If you open your browser's dev console you should see an error.

Upvotes: 1

Related Questions