0

I'd like to lazy initialize the source options of a jQueryUI autocomplete. I'm aware of the possibility to pass a function to the source option, but I want to delay the initialization until the user really starts using the autocomplete.

I tried waiting for the search event and then set the source option, but this has no effect.

var availableTags = [
    "ActionScript",
    "AppleScript",
    "Scheme"
    ];
$("#searchFirstTransactionStateInfo_searchPartnerId").autocomplete({
    source : [],
    minLength: 0,
    search: function( event, ui ) {
        $(event.target).source = availableTags;
    }
});

How can I delay setting the source option until the user starts using the UI element?

Note: I used a fixed array for simplicity. Finally I want to call an AJAX function.

3
  • how about waiting for the onclick event? Commented Jul 8, 2014 at 8:05
  • Does this work as well if the user uses keyboard navigation? Commented Jul 8, 2014 at 8:05
  • Have you tried to listen onfocus event? Commented Jul 8, 2014 at 8:08

1 Answer 1

1

Well, if you use a function as the source parameter, and let that function perform a get request (ajax ofcourse), it will actually only start making requests when you've typed something. As an example, open up your network tab and start typing in this UI example:

http://jqueryui.com/autocomplete/#multiple-remote

$(function() {
    function split( val ) {
        return val.split( /,\s*/ );
    }
    function extractLast( term ) {
        return split( term ).pop();
    }

    $( "#birds" )
    .autocomplete({
        source: function( request, response ) {
            $.getJSON( "search.php", {
                term: extractLast( request.term )
            }, response );
        },
        search: function() {
            // custom minLength
            var term = extractLast( this.value );
            if ( term.length < 2 ) {
                return false;
            }
        },
        focus: function() {
            return false;
        },
        select: function( event, ui ) {
            var terms = split( this.value );
            // remove the current input
            terms.pop();
            // add the selected item
            terms.push( ui.item.value );
            // add placeholder to get the comma-and-space at the end
            terms.push( "" );
            this.value = terms.join( ", " );
            return false;
        }
    });
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.