Dynamic Dropdown with jQuery and PHP
Live demo http://livedemo.hendrasetiawan.net/dynamic-dropdown/
This project show you how to create dynamic dropdown with jQuery and PHP.
This is a master file. First, we need to create the master dropdown :<select name="jenis" id="jenis">
<option value=''>- PILIH -</option>
<option value="BUAH">BUAH</option>
<option value="SAYUR">SAYUR</option>
</select>
And we need to create an empty dropdown :
<select name="nama" id="nama">
<option value=''>- PILIH -</option>
</select>
Next step, include jquery :
<script src="js/jquery.min.js"></script>And then, we create function to load dynamic data from helper.php :
<script>
$("#jenis").change(function() {
$("#nama").load(encodeURI("helper.php?jenis=" + $("#jenis").val()));
});
</script>
index.php. Here is the example :
$array = array(
'PISANG' => 'BUAH',
'MANGGA' => 'BUAH',
'APEL' => 'BUAH',
'BAYAM' => 'SAYUR',
'KANGKUNG' => 'SAYUR',
'BUNCIS' => 'SAYUR');
And finally, we just need to fetch the data and show it to the world :
$jenis = $_GET['jenis'];
while ($fruit_name = current($array)) {
if ($fruit_name == $jenis) {
echo "<option value = '".key($array)."'>".key($array)."</option>";
}
next($array);
}