Select2 drop-down list for countries with flags

Does anyone have a simple example of a country dropdown, with country flags, for Select2 ? I am going to implement it based on this proposal, but I would prefer not to reinvent the wheel.

+4
source share
4 answers

I worked on a similar problem, and this is how I solve it.

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

I also made a gist about this, and below are the demos.

+6
source

How 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 sprite) https://www.flag-sprites.com/

+3
source
 <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> 
+1
source

Source: https://habr.com/ru/post/1495702/


All Articles