Select2 drop-down for countries, with flags

我只是一个虾纸丫 提交于 2019-11-30 14:09:41

问题


Does somebody have an easy to use example of a country drop-down, with country flags, for Select2? I am about to implement one based on this suggestion, but I would prefer to avoid reinventing the wheel.


回答1:


I was working on a similar problem and here is how I solve it.

(function($) {
    $(function() {
        var isoCountries = [
            { id: 'AF', text: 'Afghanistan'},
            ...
        ];
        //Assuming you have a select element with name country
        // e.g. <select name="name"></select>

        $("[name='country']").select2({
            placeholder: "Select a country",
            data: isoCountries
        });
    });
})(jQuery);

I also have made a gist about it and following are the demos.

  • Demo 1
  • Demo 2 with flags based on official DOC of select2



回答2:


The way i did it:

<div class="form-group">
    <label class="control-label">Destination</label>
    <input type="text" name="cdCountry" class="form-control" required />
</div>

<script>
    $("[name='cdCountry']").select2({
        placeholder: "Select a country",
        formatResult: function (country) {
            return $(
              "<span><i class=\"flag flag-" + country.id.toLowerCase() + "\"></i> " + country.text + "</span>"
            );;
        },
        data: yourDataSource
    });
</script>

and using the css library (css and a sprite) https://www.flag-sprites.com/

Official DOC




回答3:


Have a look on the following links.

http://www.marghoobsuleman.com/countries-dropdown-flags http://vincentlamanna.com/BootstrapFormHelpers/country.html




回答4:


<head>
    <link href="select2.css" rel="stylesheet"/>
    <script src="select2.js"></script>
    <script>
        $(document).ready(function() { $("#e1").select2(); });
    </script>
</head>
<body>
    <select id="e1">
        <option value="1">Albania<img src="Albania.jpg"></option>
        ...
        <option value="2">Germany<img src="Germany.jpg"></option>
    </select>
</body>


来源:https://stackoverflow.com/questions/18099370/select2-drop-down-for-countries-with-flags

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!