How to extend the scriptaculous autocompleter?

821 Views Asked by At

The autocompleter in script.aculo.us expects that the server response is a <ul> list. Is there some way for me to extend or replace this behaviour so it can take server response that is an XML or JSON document instead?

Is there also a way to extend the autocompleter's renderer so I can add a footer to the autocompletion list?

1

There are 1 best solutions below

0
On BEST ANSWER

Yes you can extend the behaviour of script.aculo.us's autocompleter. You do this by overriding the onComplete method with code that handles the json data and creates the <ul>-list for you. This list should then be sent to updateChoices.

Say you will retrieve the following JSON response when you search for "U":

[
  "Unicorn",
  "University"
]

An example of an extension of Ajax.Autocompleter that can handle the response above:

var MyCompleter = Class.create(Ajax.Autocompleter, {

    initialize: function($super, id_search, id_list, url, options) {
        $super(id_search, id_list, url, options);
    },

    onComplete: function(response) {
        var text = response.responseText;
        if (text.isJSON()) {
            this.handleJSON(text.evalJSON());
        }
        // else do nothing
    },

    handleJSON: function(json) {
        var htmlStr = '<ul>';
        json.each(function(item) {
            htmlStr += '<li>';
            htmlStr += item;
            htmlStr += '</li>';
        });
        htmlStr += '</ul>';
        this.updateChoices(htmlStr);
    }

});

There is also an example on how to replace autocompleter's width reset behaviour.