Pppfff este tema ya se trato tantas veces.
index.html
Código HTML:
Ver original<!DOCTYPE html>
<select name="continente" data-load="continente">
<select name="pais" data-load="pais" data-depend="continente">
<select name="provincia" data-load="provincia" data-depend="continente,pais">
function depend(form) {
this.form = form;
this.init();
}
depend.prototype = {
"init" : function() {
var dependents = this.form.querySelectorAll("select[data-depend]"),
standalone = this.form.querySelectorAll("select:not([data-depend])"),
dependent;
for (var d=0; d<dependents.length; d++) {
dependent = dependents[d];
var mains = this.form.querySelectorAll("[name='" + dependent.dataset.depend.split(",").join("'],[name='") +"']");
for (var m=0; m<mains.length; m++)
mains[m].addEventListener("change", this.load.bind(this, dependent));
}
for (var s=0; s<standalone.length; s++)
this.load(standalone.item(s));
},
"load" : function(select) {
var options = select.querySelectorAll("option:not(.default)");
for (var o=0; o<options.length; o++)
select.removeChild(options.item(o));
this.ajax("combo/" + select.dataset.load + ".php", {
"success" : function(data) {
data.forEach(function(item){
var option = document.createElement("option");
option.value = item.value;
option.label = item.label;
select.appendChild(option);
});
},
"error" : function(e) {
console.log(e);
alert(e);
}
});
},
"ajax" : function(url, callbacks) {
var request = new XMLHttpRequest();
request.open("post", url);
request.onreadystatechange = function(callbacks) {
if(this.readyState === 4) {
var response = this.responseText,
success = false;
if(this.status == 200) {
try {
response = JSON.parse(response);
success = true;
} catch(e) { }
}
if(success)
if(callbacks.success)
callbacks.success(response);
else if(callbacks.error)
callbacks.error({"response" : response});
}
}.bind(request, callbacks);
request.send(new FormData(this.form));
}
}
new depend(document.getElementById("form-depend"));
combo/continente.php
Código PHP:
Ver original<?php
$continentes = [
["label" => "America", "value" => 1],
["label" => "Europa", "value" => 2],
// ...
];
combo/pais.php
Código PHP:
Ver original<?php
$paises = [
1 => [
["label" => "Argentina", "value" => 1],
["label" => "Uruguay", "value" => 2]
// ...
],
2 => [
["label" => "España", "value" => 3],
["label" => "Alemania", "value" => 4]
// ...
],
// ...
];
echo json_encode(empty($paises[$_POST["continente"]]) ?
[] : $paises[$_POST["continente"]]);
combo/provincia.php
Código PHP:
Ver original<?php
$provincias = [
1 => [
["label" => "Buenos Aires", "value" => 1],
// ...
],
2 => [
["label" => "Montevideo", "value" => 3],
// ...
],
3 => [
["label" => "Madrid", "value" => 4],
// ...
],
4 => [
["label" => "Berlin", "value" => 5],
// ...
],
// ...
];
echo json_encode(empty($provincias[$_POST["pais"]]) ?
[] : $provincias[$_POST["pais"]]);