How to get drop down menu list depend on changing the other drop down list

To get the first drop down menu to auto change the options of a second drop down list , first we will get the value of the first selected drop down list then will pass this value to the external link/url using jquery ajax() method. The external URL will send us the list of option and then we will assign that drop down list to the second drop down menu using jquery $(selector).html() method. E.g The action page will return the following option and we will assign these options to the html <select> tag. Let discuss by example.

Select cities on the behalf of country name

<script src=""></script> <select id="country"> <option>---Choose Country---</option> <option>Pakistan</option> <option>Turkey</option> </select> <select id="cities"> <option>---Cities---</option> </select> When we will select country Pakistan then the cities of Pakistan should show and when we select Turkey then the cities of Turkey should show. First we will get the country name using and will pass it to the action page cities.php and the action page will return the cities in the html <option> format. We have to assign these options to the HTML <select> of cities. <script type="text/javascript"> $("#country").on('change',function(){ var country= $(this).val(); $.ajax({ url: 'cities.php' , type: 'POST', data: "country="+country, success: function(cities) { $("#cities").html(cities); } }); }); </script>

Option returning page PHP cities.php

Database: cities <?php mysql_connect('localhost', 'root', ''); mysql_select_db('myfirstdatabase'); $query = mysql_query("SELECT name FROM cities WHERE country='".$_POST[country]."' "); while ($cities = mysql_fetch_assoc($query)) { echo '<option>'.$cities[name].'</option>'; } ?>


Chapter Next »