简体   繁体   中英

Format Select2 dropdown results having json

I am using select2 dropdown control to display list of facilities eg facility A,B,C...etc. along with its location details. I am looking for following output,

在此处输入图片说明

Currently I can display "facility name", but would like to display City and State from my json objects. How can I format my results to display them as above html format? Here's my code so far.

<input type="hidden" id="ddlFacility" style="width:100%" />

$("#ddlFacility").select2({
        placeholder: "Select a Facility",
        ajax: {
            url: "my url",
            dataType: 'json',
            type: "GET",
            quietMillis: 50,
            data: function ( term ) { return { term: term }; },
            results: function (data) {
                return {
                    results: $.map(data, function (item) {
                        return { text: item.FacilityName, id: item.FacilityId }
                    })
                };
            }
        }
    });

in your select2 options pass a function something like this and style the classes however you need

...
placeholder: "Select a Facility",
    formatResult: function(item)
    { 
         return '<div class="facility">' + item.text + '</div><span class="city">' + item.city + '</span></div>';
    },
 ...

you may need your .map function to include Facilityname and City values in addition to id and text.

If you want the selected value to look the same, use the same function for the formatSelection option

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM