Country-Region DropDown Menu is a JavaScript based dropdown menu that allows users to implement country-region list effortlessly. The region names are automatically refreshed and filled based on the country selection. And, the implementation is simple, you just need to edit a few lines of code by entering the pre-defined class name and attribute into the country and region dropdown menu respectively to make them work. In addition, there are a few more options users may configure to make the dropdown look fabulous like the default country selection, flag icon and so on.
However, this open source dropdown menu only supports up to region level. Cities data was not available in this free version. And, this tutorial is going to show you with step-by-step instruction on how to add cities dropdown to Country-Region DropDown Menu.
- Get and download World Major Cities Database from https://www.geodatasource.com/software/world-major-cities-drop-down-list-source-codes
- Unzip the downloaded GEODATASOURCE-WORLD-MAJOR-CITIES-SOURCE-CODES.ZIP file.
- Import the database into MySQL database. Note: Please refer to the sql file in the unzipped file.
- Download Country-Region DropDown Menu at https://github.com/geodatasource/country-region-dropdown-menu
- Run the following code in your site.
<?php $mydbusername = "[your username]"; $mydbpassword = "[your password]"; $mydbserver = "localhost"; $conn = new mysqli($mydbserver, $mydbusername, $mydbpassword); if (!$conn) { die('Could not connect: ' . $conn->connect_error); } $conn->select_db("countrystatecitydb") or die('Could not select database'); $conn->query("SET NAMES 'utf8'"); $sqlStr = "SELECT STATE, GROUP_CONCAT(CITY_NAME SEPARATOR '| ') AS CITY FROM countrystatecity WHERE STATE != '-' GROUP BY STATE"; $rs1 = $conn->query($sqlStr); if (!$rs1) { die('Query Error: ' . $conn->error); } ?> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Country-Region DropDown Menu with Cities</title> <script src="dist/geodatasource-crc.min.js"></script> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> <script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script> <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"> <link rel="stylesheet" href="dist/geodatasource-countryflag.css"> <?php echo '<script type="text/javascript">'; echo 'var region_cities = {};'; while ($row = $rs1->fetch_assoc()) { echo 'region_cities["' . $row["STATE"] . '"] = "' . $row["CITY"] . '";'; } echo '</script>'; ?> </head> <body> <h2>Country-Region DropDown Menu Example</h2> <div> <p>Example:</p> <p> Country: <select class="gds-cr" country-data-region-id="gds-cr-example"></select> Region: <select id="gds-cr-example" region-data-city-id="gds-cr-city_example" ></select> City: <select id="gds-cr-city_example" ></select> </p> </div> </body> </html> <?php $conn->close(); ?>
- Done.