phpMySQL

Combobox Bertingkat

Bismillah.

Dengan melihat gambar di atas pastilah sudah mengetahui apa yang dimaksud combobox bertingkat. Istilah kerennya “chained select”. Selain menggunakan php mysql juga di sini diguna jquery. Dan untuk contoh kasusnya diguna pilihan SELECT propinsi – kabupaten – kecamatan.

Scriptnya sbb:

File index.php
<html>
<head><title>Select Chain</title>
http://jquery.js

var htmlobjek;
$(document).ready(function(){
$(“#propinsi”).change(function(){
var propinsi = $(“#propinsi”).val();

$.ajax({
url: “ambilkota.php”,
data: “propinsi=”+propinsi,
cache: false,
success: function(msg){
$(“#kota”).html(msg);

}
});
});
$(“#kota”).change(function(){
var kota = $(“#kota”).val();
$.ajax({
url: “ambilkecamatan.php”,
data: “kota=”+kota,
cache: false,
success: function(msg){
$(“#kec”).html(msg);
}
});
});
});

</head>
<body>
<?php
mysql_connect(“localhost”,”root”,””);
mysql_select_db(“provkabkotkec”);
?>
Pilih Provinsi :<br>
<select name=”propinsi” id=”propinsi”>
<option>–Pilih prop–</option>
<?php
//mengambil nama-nama propinsi yang ada di database
$propinsi = mysql_query(“SELECT * FROM prov ORDER BY nama_prov”);
while($p=mysql_fetch_array($propinsi)){
echo “<option value=”$p[id_prov]”>$p[nama_prov]</option>n”;
}
?>
</select>
<br>Pilih Kabupaten/Kota :<br>
<select name=”kota” id=”kota”>
<option>–Pilih kab–</option>
<?php
//mengambil nama-nama propinsi yang ada di database
$kota = mysql_query(“SELECT * FROM kabkot ORDER BY nama_kabkot”);
while($p=mysql_fetch_array($propinsi)){
echo “<option value=”$p[id_kabkot]”>$p[nama_kabkot]</option>n”;
}
?>
</select>

<br>Pilih Kecamatan :<br>
<select name=”kec” id=”kec”>
<option>–Pilih kec–</option>
</select>
</body>
</html>

file ambilkota.php
<?php
mysql_connect(“localhost”,”root”,””);
mysql_select_db(“provkabkotkec”);
$propinsi = $_GET[‘propinsi’];
$kota = mysql_query(“SELECT id_kabkot,nama_kabkot FROM kabkot WHERE id_prov=’$propinsi’ order by nama_kabkot”);
echo “<option>– Pilih kab –</option>”;
while($k = mysql_fetch_array($kota)){
echo “<option value=””.$k[‘id_kabkot’].””>”.$k[‘nama_kabkot’].”</option>n”;
}
?>

File ambilkecamatan.php
<?php
mysql_connect(“localhost”,”root”,””);
mysql_select_db(“provkabkotkec”);
$kota = $_GET[‘kota’];
$kec = mysql_query(“SELECT id_kec,nama_kec FROM kec WHERE id_kabkot=’$kota’ order by nama_kec”);
echo “<option>– Pilih kec –</option>”;
while($k = mysql_fetch_array($kec)){
echo “<option value=””.$k[‘id_kec’].””>”.$k[‘nama_kec’].”</option>n”;
}
?>

Utnuk download code dan database di sini.

makasih.

Leave a Reply

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