Load Dependent Dropdown on Multi-Select using PHP and jQuery

by Vincy. Last modified on July 8th, 2022.

Dependent dropdowns are multiple dropdown fields whose values depends on the other dropddown and they are loaded dynamically based on user selection. The data based on which the dependent dropdown options are loaded could be supplied as an input or computed pro grammatically also.

For example, If we want to show the language locale in a dropdown depended on the region, we can either supply the region as input or compute the region programmatically by using Geo services.

View Demo

We have already seen how to load dependent dropdown based on the selected values of another dropdown. We can create dependent dropdown cascade as we have seen in the country-state-city dependent dropdown example.

In this article, we are going to see how to load the dependent dropdown options dynamically based on the multiple values selected in another dropdown.

In this example, I have shown the country list in a multi-select dropdown. On changing this dropdown, I call the jQuery AJAX to request the PHP file. In this PHP file, I received the country names selected and posted via the AJAX request.

Based on the selected country result I connect the database to fetch the states result. We can select multiple values from the country dropdown and the values are posted as an array. I have imploded the posted country name and apply MySQL IN clause to pass these values to the SELECT query.

This screenshot shows the output of the PHP jQuery multi-select dependent example.

jQuery-Multi-Select-Dependent-Dropdown-Output

Database Script

This MySQL script includes the create statement and the data dump for the country and the states tables.

CREATE TABLE IF NOT EXISTS `country` (
`id` int(11) NOT NULL,
  `country_name` varchar(255) NOT NULL
)

INSERT INTO `country` (`id`, `country_name`) VALUES
(1, 'Brazil'),
(2, 'China'),
(3, 'France'),
(4, 'India'),
(5, 'USA');

CREATE TABLE IF NOT EXISTS `states` (
`id` int(11) NOT NULL,
  `name` varchar(255) NOT NULL,
  `countryID` int(11) NOT NULL
)

INSERT INTO `states` (`id`, `name`, `countryID`) VALUES
(1, 'Sao Paulo', 1),
(2, 'Rio de Janeiro', 1),
(3, 'Ceara', 1),
(4, 'Santa Catarina', 1),
(5, 'Espirito Santo', 1),
(6, 'Beijing', 2),
(7, 'Hebei', 2),
(8, 'Jiangsu', 2),
(9, 'Guangdong', 2),
(10, 'Guangdong', 2),
(11, 'Ile-de-France', 3),
(12, 'Midi-Pyrenees', 3),
(13, 'Picardie', 3),
(14, 'Franche-Comte', 3),
(15, 'Alsace', 3),
(16, 'Haryana', 4),
(17, 'Andhra Pradesh', 4),
(18, 'Delhi', 4),
(19, 'Tamil Nadu', 4),
(20, 'Uttar Pradesh', 4),
(21, 'California', 5),
(22, 'Iowa', 5),
(23, 'New York4', 5),
(24, 'New Jersey', 5),
(25, 'Massachusetts', 5);

HTML Multi-select Dependent Dropdown

In the following HTML code, I have shown the country and state dropdowns. The country dropdown is initially loaded with the list of countries fetched from the database whereas the state dropdown has no options.

When selecting options from the countries dropdown, the getState() jQuery AJAX function will be called. This AJAX request will result in the list of state options that are loaded dynamically to the state dropdown.

<div class="frmDronpDown">
    <div class="row">
        <label>Country:</label><br /> <select name="country[]"
            id="country-list" class="demoInputBox"
            onChange="getState();" multiple size=4>
            <option value="">Select Country</option>
            <?php
foreach ($countryResult as $country) {
    ?>
            <option value="<?php echo $country["id"]; ?>"><?php echo $country["country_name"]; ?></option>
            <?php
}
?>
        </select>
    </div>
    <div class="row">
        <label>State:</label><br /> <select name="state[]"
            id="state-list" class="demoInputBox" multiple size=5>
            <option value="">Select State</option>
        </select>
    </div>
</div>

jQuery Function to Load Dependent Dropdown using AJAX

This jQuery script shows the getState() function to be called on selecting countries. This function for the comma separated string with the selected country list.

This string will be passed to the PHP code and used in a SELECT query to fetch the dependent state result. The result will be responded in the HTML format which will be reflected in the browser as the dependent options.

<script src="https://code.jquery.com/jquery-2.1.1.min.js"
    type="text/javascript"></script>
<script>
function getState() {
        var str='';
        var val=document.getElementById('country-list');
        for (i=0;i< val.length;i++) { 
            if(val[i].selected){
                str += val[i].value + ','; 
            }
        }         
        var str=str.slice(0,str.length -1);
        
	$.ajax({          
        	type: "GET",
        	url: "get_state.php",
        	data:'country_id='+str,
        	success: function(data){
        		$("#state-list").html(data);
        	}
	});
}
</script>

PHP Code to Connect State Database to Fetch Dependent Data

In PHP, the country results are received and used in a SELECT query to fetch state result. If the user selected multiple countries then the input will be posted in an imploded format via jQuery AJAX.

This imploded string is supplied to the MySQL query using IN clause. The resultant state data will be iterated to create the HTML select options. This HTML output will be responded to the AJAX block to update the UI.

<?php
require_once("DBController.php");
$db_handle = new DBController();
if(!empty($_GET['country_id'])) {
        $coun_id = $_GET["country_id"];           
	$query ="SELECT * FROM states WHERE countryID IN ($coun_id)";
	$results = $db_handle->runQuery($query);
?>
	<option value="">Select State</option>
<?php
	foreach($results as $state) {
?>
	<option value="<?php echo $state["id"]; ?>"><?php echo $state["name"]; ?></option>
<?php
	}
}
?>

View DemoDownload

Comments to “Load Dependent Dropdown on Multi-Select using PHP and jQuery”

Leave a Reply to Vincy Cancel reply

Your email address will not be published. Required fields are marked *

↑ Back to Top

Share this page