Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select2 drop-down for countries, with flags

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.

like image 311
blueFast Avatar asked Aug 07 '13 09:08

blueFast


People also ask

How do I create a dropdown Select 2?

Creating new options in the dropdown New options can be added to a Select2 control programmatically by creating a new Javascript Option object and appending it to the control: var data = { id: 1, text: 'Barn owl' }; var newOption = new Option(data. text, data.id, false, false); $('#mySelect2'). append(newOption).

How to close select2 dropdown?

$("#select2-drop-mask"). select2("close");

How do I select a Dropdownlist using jQuery?

if your options have a value, you can do this: $('select'). val("the-value-of-the-option-you-want-to-select"); 'select' would be the id of your select or a class selector. or if there is just one select, you can use the tag as it is in the example.


2 Answers

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
like image 123
Starx Avatar answered Oct 12 '22 15:10

Starx


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

like image 26
Rafael Herscovici Avatar answered Oct 12 '22 14:10

Rafael Herscovici