thowzif thowzif -4 years ago 135
MySQL Question

Show drop down values of a select based on another select

I have a table for 'Projects' as below

Project_ID | Client_ID
P1 C1
P2 C1
P3 C2
P4 C2
P5 C3
P6 C3

I have a select id="1" that shows all the Client ID's.

I'm showing an another select id="2" to show all the projects assigned to the client ID's.

Basically i want to show option values for select id="2" based on the selected value from select id="1".

Example if some one selects

<option value="C3">C3</option>

Then below should be there

<select id="2">
<option value="P5">P5</option>
<option value="P6">P6</option>

Im thinking Ajax is the answer but i dont know a proper way to do it.

Answer Source

You can add an event listener for the onChange event of the select box. On the change event get the value of the select box and send its value to the server using an ajax request and fetch the value you want to show in the second select box based on the first one's value and show it in the second select box. Example Code for state selection based on country selection:

<!DOCTYPE html>
<html lang="en">
<meta charset="UTF-8">
<title>Populate City Dropdown Using jQuery Ajax</title>
<script type="text/javascript" src=""></script>
<script type="text/javascript">
        var selectedCountry = $(".country option:selected").val();
            type: "POST",
            url: "process-request.php",
            data: { country : selectedCountry } 
                <select class="country">
                    <option value="usa">United States</option>
                    <option value="india">India</option>
                    <option value="uk">United Kingdom</option>
            <td id="response">
                <!--Response will be inserted here-->


    // Capture selected country
    $country = $_POST["country"];

    // Define country and city array
    $countryArr = array(
                    "usa" => array("New Yourk", "Los Angeles", "California"),
                    "india" => array("Mumbai", "New Delhi", "Bangalore"),
                    "uk" => array("London", "Manchester", "Liverpool")

    // Display city dropdown based on country name
    if($country !== 'Select'){
        echo "<label>City:</label>";
        echo "<select>";
        foreach($countryArr[$country] as $value){
            echo "<option>". $value . "</option>";
        echo "</select>";
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download