Auto load options when PHP / MySQL option is selected

I have a problem with the code I am working on. I am obviously new to php and mySQL. I want to load a parameter field from mysql database when another option is selected. That is: I have options

<select name=state>
   <option value=Lagos>Lagos</option>
   <option value=Abuja>Abuja</option>
   <option value=Rivers>Rivers</option>
   </select>

      

and another set of parameters:

   <select name=City>
   <option value=Lekii>Lekki</option>
   <option value=VI>VI</option>
   <option value=Ikoyi>Ikoyi</option>
   </select>

      

I have a database called LOCATION , and tables for state and city I want to load the corresponding list of cities when the state is selected. That is, when I select Lagos, all Lagos cities will be populated in another dropdown menu.

Please note that there are 2 Select fields.

Please help me guys.

+3


source to share


2 answers


Based on application architecture and preferences:

You can make an ajax call to the server every time to get the corresponding cities based on the selected state. Follow the post Autocomplete select box with jQuery and AJAX .

Or

you can preload all state based cities in JSON format and show the corresponding city based on the selected state. See my working example here on the Jsfiddle.



<head>
    <title></title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
    <script type="text/javascript">
     // you need to fill this cities value getting data from city table of your DB
cities = {
    "Lagos": ["LagosCity1", "LagosCity2"],
    "Abuja": ["AbujaCity1", "AbujaCity2", "AbujaCity3"],
    "Rivers": ["RiversCity1", "RiversCity2", "RiversCity3"]
}
$(document).ready(function() {
  $('#state').change(function() {
       var state = $(this).val();
    if(cities[state] && cities[state].length > 0)
    $("#Scity").html('');
     $.each(cities[state], function(i, city) {
            $("<option>").attr("value", city).text(city).appendTo("#Scity");
        });
  });
});
</script>
</head>
<body>
State: <select id='state' name='state'>
   <option value=0>Select</option>
   <option value='Lagos'>Lagos</option>
   <option value='Abuja'>Abuja</option>
   <option value='Rivers'>Rivers</option>
</select>
City: <select id="Scity" name='city'></select>
</body>
</html>

      

Or

You can by default display all your cities in the city selection box and filter cities while a state is selected and only show cities belonging to that state, see an example here .

+6


source


You need to use an Ajax call to get data based on the selected state.



+3


source







All Articles