Search code examples
javascriptjsonpgeonames

Unable to select items populated via jsonp in select2


I'm trying to populate a select2 element using geonames data. I have a formatSelection method defined but it will not fire when an item is selected.

Here's the HTML element:

<input id="location" size="30" type="text">​

Select2 binding with format functions:

function locationFormatResult(location) {
    var markup = "<table class='location-result'><tr>";

    if (location.countryCode !== undefined) {
        markup += "<td class='flag-image'><img src='http://www.geonames.org/flags/x/" + location.countryCode.toLowerCase() + ".gif' /></td>";
    }

    markup += "<td class='location-info'>";
    markup += "<div class='location-name'>" + location.name + ", " + location.adminName1 + ", " + location.countryName + "</div>";
    markup += "</td></tr></table>";

    return markup;
}

function locationFormatSelection(location) {
    return location.name + ", " + location.adminName1 + ", " + location.countryName;
}

$(function () {
    $('#location').select2({
        placeholder: 'Location',
        allowClear: true,
        width: '260px',
        minimumInputLength: 2,
        ajax: {
            url: 'http://ws.geonames.org/searchJSON',
            dataType: 'jsonp',
            data: function (term) {
                return {
                    featureClass: 'P',
                    q: term
                };
            },
            results: function (data) {
                return {
                    results: data.geonames
                };
            }
        },
        formatResult: locationFormatResult,
        formatSelection: locationFormatSelection,
        dropdownCssClass: "bigdrop"
    });
});

You can see the full fiddle here: http://jsfiddle.net/6CVbw/1/

Why is selecting an item not working?


Solution

  • I figured it out. When you instantiate the select2 plugin on an element you have to specify an ID attribute. This worked:

    $(function () {
        $('#location').select2({
            id: function(e) { return e.name + '|' + e.adminName1 + '|' + e.countryName },
            placeholder: 'Location',
            allowClear: true,
            width: '260px',
            minimumInputLength: 2,
            ajax: {
                url: 'http://ws.geonames.org/searchJSON',
                dataType: 'jsonp',
                data: function (term) {
                    return {
                        featureClass: 'P',
                        q: term
                    };
                },
                results: function (data) {
                    return {
                        results: data.geonames
                    };
                }
            },
            formatResult: locationFormatResult,
            formatSelection: locationFormatSelection,
            dropdownCssClass: "bigdrop"
        });
    });
    

    You can see the updated fiddle here: http://jsfiddle.net/6CVbw/2/