JQuery autocomplete with ranged fields

  • 0
Few weeks ago I was looking for a way to get a form field autocomplete from a remote JSON file with a single HTTP request. The solution is here.
Now I want to do the same but using ranged fields (i.e., sort of an array where commas separate items and hyphen define ranges). A valid field would be: 1-8,10,13,15-20.

Here the javascript / JQuery code:
    /* Function to populate the autocomplete from a remote json.
      For ranged fields, .e.g,: 4588-4590,465-658 */
    function split(val) {
        return val.split(/[,-]\s*/);

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

    function set_autocomplete_ranged(selector, jsonurl) {
            url: jsonurl,
            type: 'get',
            dataType: 'json',
            async: true,
            success: function (data) {                
                    minLength: 0,
                    source: function (request, response) {
                        data, extractLast(request.term) ));
                    focus: function () {
                        return false;
                    select: function (event, ui) {
                        var this_value = ui.item.value
                        var all_values = this.value
                        this.value = all_values + this_value
                        return false;
                }).bind('focus', function () {
                    if (!$(this).val().trim()) $(this).keydown();
An then just add the URL for the JSON and the id for the field you want to use the ranged autocomplete:
    Function called only once! It populates the autocomplete from a remote json.
    The filtering is made locally as the source is a local variable :)
    $(function() {
        var jsonurl = "http://mysite.com/myjson.json";
        var selector = '#id_ranged_field';
        if  ($(selector).is('*')) {

No comments:

Post a Comment