Skip to content
the poor coder

cargar un select con javascript dependiendo de otro select

Poor Man
Published
Reading time
3 min read
On this page

Cargar un select con javascript dependiendo de otro select#

Si desea cargar un select con javascript dependiendo de otro select, es posible mediante el uso de eventos y AJAX. Por ejemplo, si tiene un select para seleccionar el país y desea cargar otro select con las ciudades de ese país seleccionado, puede hacerlo fácilmente utilizando javascript.

Paso 1: Crear los selects#

Primero, debemos crear los dos selects en nuestro HTML:

Text
<label for="country-select">País:</label>
<select id="country-select">
  <option value="usa">Estados Unidos</option>
  <option value="canada">Canadá</option>
  <option value="mexico">México</option>
</select>

<label for="city-select">Ciudad:</label>
<select id="city-select"></select>

Paso 2: Agregar un evento al select del país#

A continuación, agregamos un evento al select del país para que cuando cambie su valor, se carguen las ciudades correspondientes:

Text
const countrySelect = document.getElementById('country-select');
const citySelect = document.getElementById('city-select');

countrySelect.addEventListener('change', () => {
  // Cargar las ciudades correspondientes
});

Paso 3: Crear una función para cargar las ciudades#

Luego, necesitamos crear una función que cargue las ciudades correspondientes utilizando AJAX:

Text
function loadCities(country) {
  // Crear una instancia de XMLHttpRequest
  const xhr = new XMLHttpRequest();
  
  // Configurar la solicitud
  xhr.open('GET', `/api/cities?country=${country}`);
  
  // Manejar la respuesta
  xhr.onload = () => {
    if (xhr.status === 200) {
      // Limpiar el select de ciudades
      citySelect.innerHTML = '';
      
      // Agregar las opciones de ciudades
      const cities = JSON.parse(xhr.responseText);
      cities.forEach(city => {
        const option = document.createElement('option');
        option.value = city.id;
        option.text = city.name;
        citySelect.appendChild(option);
      });
    } else {
      console.error(xhr.statusText);
    }
  };
  
  // Manejar los errores de red
  xhr.onerror = () => {
    console.error(xhr.statusText);
  };
  
  // Enviar la solicitud
  xhr.send();
}

Paso 4: Llamar a la función para cargar las ciudades#

Finalmente, llamamos a la función para cargar las ciudades dentro del evento del select del país:

Text
countrySelect.addEventListener('change', () => {
  const country = countrySelect.value;
  loadCities(country);
});

Aquí está el código completo:

Text
<label for="country-select">País:</label>
<select id="country-select">
  <option value="usa">Estados Unidos</option>
  <option value="canada">Canadá</option>
  <option value="mexico">México</option>
</select>

<label for="city-select">Ciudad:</label>
<select id="city-select"></select>

<script>
const countrySelect = document.getElementById('country-select');
const citySelect = document.getElementById('city-select');

function loadCities(country) {
  const xhr = new XMLHttpRequest();
  
  xhr.open('GET', `/api/cities?country=${country}`);
  
  xhr.onload = () => {
    if (xhr.status === 200) {
      citySelect.innerHTML = '';
      
      const cities = JSON.parse(xhr.responseText);
      cities.forEach(city => {
        const option = document.createElement('option');
        option.value = city.id;
        option.text = city.name;
        citySelect.appendChild(option);
      });
    } else {
      console.error(xhr.statusText);
    }
  };
  
  xhr.onerror = () => {
    console.error(xhr.statusText);
  };
  
  xhr.send();
}

countrySelect.addEventListener('change', () => {
  const country = countrySelect.value;
  loadCities(country);
});
</script>

Este es solo un ejemplo y puede adaptarse a cualquier necesidad similar. También es posible utilizar frameworks como React, Angular o Vue para simplificar el código y hacerlo más fácil de mantener.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC