Generate a List of Dynamic Cities Based on the Selected State

funnelish

Hi Funnelish team and community
I need urgent help please

For example, I need for a Department and City use case.

In other words, if the user selects “LA LIBERTAD” in the input [shipping_state] “Department” then in the next input [shipping_city] “City” it should show only a custom list that it adds.

I tried using this javascript snippet but I don’t get the result I need.

Here the code:

<script>
document.addEventListener('DOMContentLoaded', function() {
  const stateInput = document.querySelector('input[name="shipping_state"]');
  const cityInput = document.querySelector('input[name="shipping_city"]');

  stateInput.addEventListener('input', function() {
    const stateValue = stateInput.value.trim();
    let cityOptions = [];

    if (stateValue === "La Libertad") {
      cityOptions = ["Trujillo", "Chicama", "Chimbote"];
    } else if (stateValue === "Cajamarca") {
      cityOptions = ["Saipo", "Lino", "Safajeta"];
    }

    cityInput.innerHTML = ""; 

    cityOptions.forEach(function(city) {
      const option = document.createElement('option');
      option.value = city;
      option.textContent = city;
      cityInput.appendChild(option);
    });
  });
});
</script>

I stay tuned thank you very much

1 Like

Hi @JoysonLlapo,

Please follow these simple instructions in order to reach such functionality:
Before we get to it, here is a live example for reference: dynamic states/cities element
Here is its share link: dynamic states/cities element

1- Adding Elements:

You will need to add a Select input form, which should be set up like so:


The options must be updated to SV as the Name and El Salvador as the value.

Later on, add Two custom dropdown elements. The first should function as the States dropdown:


The other is for Cities:

2- Giving the Elements suitable classes.

Select Each of the elements we added in the previous step, Go to Advanced, and give them the following classes:
my_dynmaic_country_box: for the countries Element.
my_dynamic_province: for the Provinces/States Element.
my_dynamic_district: for the Districts/Cities Element.
Example:
image

3- Adding the custom JS code:

Now go to Custom Codes > Custom JS (Body) and paste the following:

<script>
let provincesMap = {
  "EC": {
    "provinces": {
      "Azuay": [
        "Cuenca",
        "Paute",
        "Sigsig",
        "Chordeleg",
        "Girón",
        "Nabón",
        "Oña",
        "Pucará",
        "San Fernando",
        "Santa Isabel",
        "Sevilla de Oro",
        "Chiquintad"
      ],
      "Bolívar": [
        "Guaranda",
        "Las Naves",
        "Chimbo",
        "Echeandía",
        "San José de Chimbo",
        "Caluma",
        "Las Mercedes"
      ],
      "Cañar": [
        "Azogues",
        "Cañar",
        "Déleg",
        "La Troncal",
        "Suscal",
        "El Tambo"
      ],
      "Carchi": [
        "Tulcán",
        "Espejo",
        "Mira",
        "Bolívar",
        "San Pedro de Huaca"
      ],
      "Chimborazo": [
        "Riobamba",
        "Colta",
        "Chambo",
        "Chunchi",
        "Guano",
        "Pallatanga",
        "Penipe"
      ],
      "Cotopaxi": [
        "Latacunga",
        "Pujilí",
        "Salcedo",
        "Saquisilí",
        "Sigchos",
        "Cotopaxi",
        "Pangua",
        "Lasso"
      ],
      "El Oro": [
        "Machala",
        "Santa Rosa",
        "Zaruma",
        "Atahualpa",
        "Balsas",
        "Chilla",
        "El Guabo",
        "Huaquillas",
        "Marcabelí",
        "Piñas",
        "Portovelo"
      ],
      "Esmeraldas": [
        "Esmeraldas",
        "Eloy Alfaro",
        "Muisne",
        "Quinindé",
        "San Lorenzo"
      ],
      "Galápagos": [
        "Puerto Baquerizo Moreno",
        "Santa Cruz"
      ],
      "Guayas": [
        "Guayaquil",
        "Durán",
        "Samborondón",
        "Milagro",
        "Naranjal",
        "Yaguachi",
        "Alfredo Baquerizo Moreno (Juján)",
        "Balao",
        "Balzar",
        "Colimes",
        "Coronel Marcelino Maridueña",
        "El Empalme",
        "El Triunfo",
        "General Antonio Elizalde (Bucay)",
        "Isidro Ayora",
        "Lomas de Sargentillo",
        "Marcelino Maridueña",
        "Milagro",
        "Naranjito",
        "Naranjal",
        "Nobol",
        "Palestina",
        "Pedro Carbo",
        "Playas",
        "Salitre",
        "San Jacinto de Yaguachi",
        "Santa Lucía",
        "Simón Bolívar"
      ],
      "Imbabura": [
        "Ibarra",
        "Antonio Ante",
        "Cotacachi",
        "Pimampiro",
        "San Miguel de Urcuquí"
      ],
      "Loja": [
        "Loja",
        "Catamayo",
        "Celica",
        "Chaguarpamba",
        "Espíndola",
        "Gonzanamá",
        "Macará",
        "Paltas",
        "Puyango",
        "Quilanga",
        "Saraguro",
        "Sozoranga",
        "Zapotillo"
      ],
      "Los Rios": [
        "Babahoyo",
        "Baba",
        "Mocache",
        "Montalvo",
        "Palenque",
        "Puebloviejo",
        "Urdaneta",
        "Valencia",
        "Ventanas",
        "Vinces"
      ],
      "Manabí": [
        "Portoviejo",
        "El Carmen",
        "Jipijapa",
        "Junín",
        "Manta",
        "Montecristi",
        "Paján",
        "Rocafuerte",
        "Santa Ana",
        "Sucre",
        "Tosagua"
      ],
      "Morona Santiago": [
        "Morona",
        "Limón Indanza",
        "Logroño",
        "Pablo Sexto",
        "Palora",
        "San Juan Bosco",
        "Santiago",
        "Sucúa",
        "Taisha",
        "Tiwintza"
      ],
      "Napo": [
        "Tena",
        "Carlos Julio Arosemena Tola",
        "El Chaco",
        "Quijos"
      ],
      "Orellana": [
        "Puerto Francisco de Orellana",
        "Loreto",
        "Aguarico"
      ],
      "Pastaza": [
        "Puyo",
        "Mera",
        "Santa Clara"
      ],
      "Pichincha": [
        "Quito",
        "Mejía",
        "Pedro Moncayo",
        "Rumiñahui",
        "San Miguel de los Bancos",
        "Pedro Vicente Maldonado",
        "Puerto Quito"
      ],
      "Santa Elena": [
        "Santa Elena",
        "Salinas",
        "La Concordia"
      ],
      "Santo Domingo de los Tsáchilas": [
        "Santo Domingo"
      ],
      "Sucumbíos": [
        "Lago Agrio",
        "Cuyabeno",
        "Putumayo"
      ],
      "Tungurahua": [
        "Ambato",
        "Pelileo",
        "Patate",
        "Píllaro",
        "Quero",
        "Tisaleo"
      ],
      "Zamora Chinchipe": [
        "Zamora",
        "Zumbi",
        "Centinela del Cóndor",
        "Nangaritza",
        "Palanda",
        "Chinchipe"
      ]
    }
  },
  "PE": {
    "provinces": {
      "LIMA":["Ancón",
        "Ate",
        "Barranco",
        "Bellavista",
        "Breña",
        "Callao",
        "Campoy",
        "Carabayllo",
        "Carapongo (SJL)",
        "Cercado de Lima",
        "Chaclacayo",
        "Chorrillos",
        "Chosica",
        "Chosica - Ricardo Palma",
        "Cieneguilla",
        "Comas",
        "El Agustino",
        "Embajadores (playa)",
        "Huaycan (Ate)",
        "Independencia",
        "Jesus Maria",
        "Jicamarca (SJL)",
        "Jose Galvez",
        "La Marina",
        "La Molina",
        "La Perla",
        "La Punta",
        "La Victoria",
        "Lince",
        "Los Olivos",
        "Lurin",
        "Magdalena",
        "Manchay",
        "Mariategui (SJL)",
        "Miraflores",
        "Oquendo",
        "Pachacamac",
        "Pueblo Libre",
        "Puente Piedra",
        "Rimac",
        "Salamanca",
        "San Antonio de Huarochiri (SJL)",
        "San Bartolo",
        "San Borja",
        "San Gabriel",
        "San Isidro",
        "San Luis",
        "San Miguel",
        "Santa Anita",
        "Santa Clara",
        "Santa Rosa",
        "Santa Maria (playa)",
        "SJLurigancho",
        "SJuanMiraflores",
        "SMP",
        "Surco",
        "Surco",
        "Surquillo",
        "Ventanilla",
        "Villa el Salvador",
        "Villa Maria del Triunfo",
        "Pucusana"
      ],
      "AREQUIPA":["Alto Selva Alegre",
        "Cayma",
        "Cerro Colorado",
        "Characato",
        "Cercado",
        "Jacobo Hunter",
        "JLBR",
        "Mariano Melgar",
        "Miraflores",
        "Paucarpata",
        "Sabandía",
        "Sachaca",
        "Socabaya",
        "Tiabaya",
        "Uchumayo",
        "Yanahuara",
        "Yura"
      ],
      "CHICLAYO":["Chiclayo",
        "La Victoria",
        "Jose Leonardo Ortiz",
        "Pimentel",
        "Caleta San Jose",
        "Reque",
        "Lambayeque Cercado",
        "Lambayeque Alrededores",
        "Monsefú",
        "Caleta Santa Rosa",
        "Ciudad y Pto Eten",
        "Pomalca",
        "Picsi",
        "Ferreñafe",
        "Tuman",
        "Mochumi",
        "Tucume",
        "Illimo",
        "Jayanca"
      ],
      "TRUJILLO":["Huanchaco",
        "Parque Industrial",
        "Manuel Arevalo",
        "Las Delicias",
        "Laredo",
        "El Milagro",
        "Victor Larco",
        "Trujillo",
        "Buenos Aires",
        "La Esperanza",
        "El Porvenir",
        "Moche",
        "Florencia de Mora",
        "Salaverry",
        "Alto Trujillo",
        "Alto Moche"
      ],
      "PIURA":["Piura",
        "El chipe, Gobierno Regional",
        "Los cocos del Chipe",
        "Urb. Quinta Ana María",
        "San Eduardo",
        "Los Geranios",
        "Santa María del Pinar",
        "La Providencia",
        "Universidad de Piura",
        "Centro de Piura",
        "18 de Mayo",
        "Almirante Grau I y II",
        "Víctor Raúl",
        "José Olaya",
        "Los Titanes I y II",
        "Sullana",
        "Inclán",
        "Rómulo León",
        "San Pedro",
        "Buenos Aires",
        "Banco de la Nación",
        "La Clark",
        "San Ramón",
        "Pachitea",
        "Santa Isabel",
        "Angamos",
        "San Felipe",
        "Ignacio Merino I y II",
        "Los Jardines – Avifap",
        "Zona Industrial  I",
        "Mercado",
        "San José",
        "Consuelo Velasco",
        "López Albujar",
        "Urb. Piura",
        "Las Mercedes",
        "La Alborada",
        "Los Ficus I y II",
        "Los Tallanes",
        "Santa Rosa",
        "Micaela Bastidas",
        "Bancarios I ETAPA S/.7 II ETAPA",
        "San Julia",
        "Quinta julia",
        "Bello Horizonte",
        "Santa Margarita",
        "Micaela I y II",
        "Enace",
        "Los Ejidos",
        "Urb. Los sauces",
        "Urb. Los jardines de la PNP",
        "Educadores",
        "11 de abril",
        "Fátima",
        "Santa Ana",
        "Vicus",
        "Casuarinas los portales",
        "San Isidro",
        "Urb. El Gold",
        "Urb. Porto Bello",
        "Catacaos",
        " Castilla",
        "Chulucanas",
        "Tambogrande",
        "26 de Octubre",
        "Paita",
        "Sechura"
      ],
      "OTRA PROVINCIA":["Amazonas",
        "Ancash",
        "Apurimac",
        "Ayacucho",
        "Cajamarca",
        "Cusco",
        "Huancavelica",
        "Huanuco",
        "Ica",
        "Junín",
        "La Libertad",
        "Lambayeque",
        "Loreto",
        "Madre de Dios",
        "Moquegua",
        "Pasco",
        "Puno",
        "San Martín",
        "Tacna",
        "Tumbes",
        "Ucayali"
      ]
    }
  }
}

</script>

<script>
let cc = document.querySelector('.my_dynmaic_country_box select');
let provincesB = document.querySelector('.my_dynamic_province select');
let districtsB = document.querySelector('.my_dynamic_district select');

cc.addEventListener('change', (ev)=>{
    let c = provincesMap[cc.value||'EC'];
    let frag = document.createDocumentFragment();
    if (provincesB.dataset.placeholder) {
        let e = document.createElement("option");
        e.disabled = true;
        e.value = "";
        e.innerText = provincesB.dataset.placeholder;
        frag.appendChild(e);
    }
    Object.keys(c.provinces).forEach(province =>{
        let e = document.createElement("option");
        e.value = province;
        e.innerText = province;
        frag.appendChild(e);
    })
    provincesB.innerHTML = ''
    provincesB.appendChild(frag.cloneNode(true))
    provincesB.value = ''
})
provincesB.addEventListener('change', (ev)=>{
    let c = provincesMap[cc.value||'EC'];
    let districts = c.provinces[provincesB.value||''];
    
    let frag = document.createDocumentFragment();
    if (districtsB.dataset.placeholder) {
        let e = document.createElement("option");
        e.disabled = true;
        e.value = "";
        e.innerText = districtsB.dataset.placeholder;
        frag.appendChild(e);
    }
    districts.forEach(district =>{
        let e = document.createElement("option");
        e.value = district;
        e.innerText = district;
        frag.appendChild(e);
    })
    districtsB.innerHTML = ''
    districtsB.appendChild(frag.cloneNode(true))
    districtsB.value = ''
})
cc.dispatchEvent(new Event('change',{bubbles:true}))

</script>

PS: Simply adding the above code inside a Custom HTML Element works fine too.

3- Updating the code:

So far, the code should work fine, but it is for Peru and Ecuador. So we’ll need to update the code for El Salvador.
Update the value of provincesMap to be something like this:

 let provincesMap = {
      "SV": {
         "provinces": {
            "La Libertad": [
               "Trujillo",
               "Chicama",
               "Chimbote"
            ],
            "Cajamarca": [
               "Saipo",
               "Lino",
               "Safajeta"
            ]
         }
      },
   }

Feel free to add any other cities, states, or countries.

Let us know how it goes.

Best,
Fey @Funnelish.

2 Likes

It works perfectly, thanks for the contribution :gift_heart:

1 Like