Add Dropdown Country & State List Dynamically into HTML form by Javascript

You can use a JavaScript to add all the country names and  state names’ Dropdown list. Which is actually done by HTMLand tag. I’ve written a JavaScript which can be simply inserted into your HTML file. Later, call my pre-defined functions and the country and state list will be automatically added into your HTML 🙂

Live Demo!

Check the code live here

How to use?

1. Copy the JavaScript code from the above link and save it in a file “countries.js”

2. Put this code between yourandsection:

<script type= "text/javascript" src = "countries.js"></script>

3. Put this code between yourandsection:

 Select Country (with states):   <select id="country" name ="country"></select>
Select State: <select name ="state" id ="state"></select>
 <script language="javascript">
populateCountries("country", "state");
 </script>

Please note that, we are using twotags, which are actual drop-down boxes. Here I’ve chosen “country” and “state” as theirID attribute. You can choose any othe id attribute or name attribute as you like. But whatever you choose, you make to pass the correct IDs when calling the JavaScript Functions.

If you only want Country list to appear on the page, Simply use following bit of code in Body section:

Select Country:   <select id="country2" name ="country2"></select>
<script language="javascript">
populateCountries("country2");
 </script>
Advertisements