I have this old code and I want it to be easier to understand. Originally, it loaded using an onload on the opening body tag, so I managed to change that to a window.onload, but now redundant code is getting elements by ID, since it first finds the form and after that the actual select box.
var localidades = new Array(
new Array("Baja California","Tijuana","Rosarito","Ensenada","Tecate","Mexicali","San Felipe"),
new Array("Sonora","San Luis Río Colorado","Sonoita","Sásabe","Nogales","Naco","Agua Prieta"),
new Array("Chihuahua","El Berrendo","Puerto Palomas","San Jerónimo","Ciudad Juárez","El Porvenir","Ojinaga"),
new Array("Coahuila","Ciudad Acuña","Piedras Negras"),
new Array("Nuevo León","Colombia"),
new Array("Tamaulipas","Nuevo Laredo","Reynosa","Río Bravo","Nuevo Progreso","Matamoros")
);
function seleccionLocal(selection){
var cajon = document.getElementById("forma1").city;
for(var x=0;x<localidades.length;x++){
if(selection==localidades[x][0]){
var cities = localidades[x];
cajon.length = cities.length;
for(var n=1;n<cities.length;n++){
cajon[n] = new Option(cities[n],cities[n]);
}
break;
}
}
}
window.onload = function StartIt(){
var cajon = document.getElementById("forma1").country;
cajon.length = localidades.length+1;
for(var x=0;x<localidades.length;x++){
cajon[x+1] = new Option(localidades[x][0],localidades[x][0]);
}
}
<form id="forma1" action="" onsubmit="" style="margin:auto;">
<select name="country" onchange="seleccionLocal(this.options[this.selectedIndex].value)">
<option value="-1" >Estado</option>
</select>
<select name="city">
<option value="-1" >Ciudad</option>
</select>
</form>
It's working, but I guess it can be lighter. What say You?