Without using jQuery, only Javascript.
I want to add the options of the second select depending on the value that the first select takes. The first select selects the province we want to deal with, and automatically depending on the province we choose, the second select (towns) is loaded with data.
HTML code:
<tr>
<td align=right>Provincia:</td>
<td align=left colspan=3>
<select name="provincia" id="provincia">
<option value="cargar_provincias();">Seleccione una Provincia...
</select>
</td>
</tr>
<tr>
<!-- Extra: Cargar pueblos a partir de una provincia -->
<td align=right>Pueblo:</td>
<td align=left colspan=3>
<select name="pueblo" id="pueblo">
<option value="cargar_pueblos();">Seleccione un Pueblo...
</select>
</td>
</tr>
Javascript code:
//Función para cargar las provincias al campo "select".
function cargarProvincias() {
//Inicializamos el array.
var array = ["Cantabria", "Asturias", "Galicia", "Andalucia", "Extremadura"];
//Ordena el array alfabeticamente.
array.sort();
//Pasamos a la funcion addOptions(el ID del select, las provincias cargadas en el array).
addOptions("provincia", array);
}
//Función para agregar opciones a un <select>.
function addOptions(domElement, array) {
var selector = document.getElementsByName(domElement)[0];
//Recorremos el array.
for (provincia in array) {
var opcion = document.createElement("option");
opcion.text = array[provincia];
selector.add(opcion);
}
}
//Función para cargar los pueblos al campo "select" dependiendo de la provincia elegida.
function cargarPueblos() {
//Objeto de provincias con los pueblos correspondientes.
var listaPueblos = {
cantabria: ["Laredo", "Gama", "Solares", "Castillo", "Santander"],
asturias: ["Langreo", "Villaviciosa", "Oviedo", "Gijon", "Covadonga"],
galicia: ["Tui", "Cambados", "Redondella", "Porriño", "Ogrove"],
andalucia: ["Dos Hermanas", "Écija", "Algeciras", "Marbella", "Sevilla"],
extremadura: ["Caceres", "Badajoz", "Plasencia", "Zafra", "Merida"]
}
//Declaramos un array donde guardamos todos los elementos de tipo id=provincias e id=pueblos.
var provincias = document.getElementById('provincia');
var pueblos = document.getElementById('pueblo');
//Tomamos como provinciaSeleccionada, el valor del id provincia (var provincias).
var provinciaSeleccionada = provincias.value;
//Se limpian los pueblos.
pueblos.innerHTML = '<option value="">Seleccione un Pueblo...</option>'
//Si existe provinciaSeleccionada...
if(provinciaSeleccionada !== ""){
//Se seleccionan los pueblos y se ordenan.
provinciaSeleccionada = listaPueblos[provinciaSeleccionada];
provinciaSeleccionada.sort();
//Insertamos los pueblos mediante un FOR.
provinciaSeleccionada.forEach(function(pueblo){
var opcion = document.createElement('option');
opcion.value = pueblo;
opcion.text = pueblo;
pueblos.add(opcion);
});
}
}
How can I make it so that when choosing a province the towns of that province are automatically loaded?
A possible solution would be to store the provinces as properties in an object, with the towns in the array as value , and when choosing province we print its array as options of the select 'town':
I have deleted your comments so that you can better identify mine.
First of all, I don't know if the function of loading the first select with the provinces works for you, I would put the method
cargarProvincias()
so that it is executed as soon as the page is loaded:Now, to load the towns in that province, add an event
onchange
to the select:So what I have done is, every time you change the province, you call the method
cargarPueblos
and pass the onevalue
of the chosen option.And it would be something like this. In arraySelected put the Array you choose, you have to base it on the value you pass to the method.