简体   繁体   English

格式化具有json的Select2下拉结果

[英]Format Select2 dropdown results having json

I am using select2 dropdown control to display list of facilities eg facility A,B,C...etc. 我正在使用select2下拉控件来显示设施列表,例如设施A,B,C ...等。 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. 目前,我可以显示“设施名称”,但是想从我的json对象显示城市和州。 How can I format my results to display them as above html format? 如何格式化结果以将其显示为以上html格式? 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 在您的select2选项中传递类似这样的函数并设置类的样式,但是您需要

...
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. 您可能需要您的.map函数,除了id和text之外还包括设施名称和城市值。

If you want the selected value to look the same, use the same function for the formatSelection option 如果希望所选值看起来相同,请对formatSelection选项使用相同的功能

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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