views:

91

answers:

2

I need an auto-complete in the app I'm working on and, since I'm already using jQuery UI, I'm trying to make its Autocomplete widget meet my needs.

Step one is to make the search term only match at the beginning of suggested terms. I've already got that working, as you can see in the code below. Step two is to have the first suggestion actually autocomplete.

Which probably requires a bit of explanation. When I hear "autocomplete", I envision typing "f" and having the contents of the text field change to "foo", with the "oo" selected, so that it is replaced if I type another character and left in the field if I tab out of it. I'd normally call what the Autocomplete widget does suggesting, rather than autocompleting.

Looking at how Autocomplete works internally, I think the autocompleteopen event is the correct place to do this (it's called every time the list of suggestions is updated), but I'm at a loss as to how to access the suggestion list from there.

Any thoughts?

$("#field").autocomplete({
    delay: 0,

    source: function filter_realms(request, response) {
        var term = request.term.toLowerCase();
        var length = term.length;

        response($.grep(candidates, function(candidate) {
            return candidate.substring(0, length).toLowerCase() === term;
        }));
    },

    open: function(event, ui) {
        // magic happens here?
    }
});
+2  A: 

Got it. I'd forgotten that widgets can be accessed via .data().

$("#field").autocomplete({
    delay: 0,

    source: function filter_realms(request, response) {
        var term = request.term.toLowerCase();
        var length = term.length;

        response($.grep(candidates, function(candidate) {
            return candidate.substring(0, length).toLowerCase() === term;
        }));
    },

    open: function(event, ui) {
        var current = this.value;
        var suggested = $(this).data("autocomplete").menu.element.find("li:first-child a").text();

        this.value = suggested;
        this.setSelectionRange(current.length, suggested.length);
    }
});
Ben Blank