0% found this document useful (0 votes)
28 views16 pages

Javascript Desplegables

The document describes how to create cascading/dependent dropdowns using JavaScript and jQuery. It defines arrays of options for provinces/states for different countries. When the country dropdown value changes, it evaluates the appropriate province array and populates the second dropdown dynamically. jQuery is also used in another example to populate dependent dropdowns from a JSON object of country/state data.

Uploaded by

Verónica Felipe
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views16 pages

Javascript Desplegables

The document describes how to create cascading/dependent dropdowns using JavaScript and jQuery. It defines arrays of options for provinces/states for different countries. When the country dropdown value changes, it evaluates the appropriate province array and populates the second dropdown dynamically. jQuery is also used in another example to populate dependent dropdowns from a JSON object of country/state data.

Uploaded by

Verónica Felipe
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 16

https://stackoverflow.

com/questions/18351921/how-to-populate-a-cascading-dropdown-
with-jquery

function populate(s1, s2) {


var s1 = document.getElementById(s1);
var s2 = document.getElementById(s2);
s2.innerHTML = "";
if (s1.value == "Germany") {
var optionArray = ["|", "magdeburg|Magdeburg", "duesseldorf|Duesseldorf", "leinfelden-
echterdingen|Leinfelden-Echterdingen", "eschborn|Eschborn"];
} else if (s1.value == "Hungary") {
var optionArray = ["|", "pecs|Pecs", "budapest|Budapest", "debrecen|Debrecen"];
} else if (s1.value == "Russia") {
var optionArray = ["|", "st. petersburg|St. Petersburg"];
} else if (s1.value == "South Africa") {
var optionArray = ["|", "midrand|Midrand"];
} else if (s1.value == "USA") {
var optionArray = ["|", "downers grove|Downers Grove"];
} else if (s1.value == "Mexico") {
var optionArray = ["|", "puebla|Puebla"];
} else if (s1.value == "China") {
var optionArray = ["|", "beijing|Beijing"];
} else if (s1.value == "Spain") {
var optionArray = ["|", "barcelona|Barcelona"];
}

for (var option in optionArray) {


var pair = optionArray[option].split("|");
var newOption = document.createElement("option");
newOption.value = pair[0];
newOption.innerHTML = pair[1];
s2.options.add(newOption);
}
};
JAVASCRIPT + JQUERY 1.10.1

$(document).ready(function () {

$('#country').change(function () {

$('#location').text() == " ";

if ($('#country option:selected').text() == "Germany") {

$('#location').append('<option value="Magdeburg">Magdeburg</option><option
value="Duesseldorf">Duesseldorf</option><option value="Leinfelden-
Echterdingen">Leinfelden-Echterdingen</option><option
value="Eschborn">Eschborn</option>')

} else if ($('#country option:selected').text == "Hungary") {

$('#location').append('<option value="Pecs">Pecs</option><option
value="Budapest">Budapest</option><option value="Debrecen">Debrecen</option>')

} else if ($('#country option:selected').text == "Russia") {

$('#location').append('<option value="St. Petersburg">St. Petersburg</option>')

} else if ($('#country option:selected').text == "South Africa") {

$('#location').append('<option value="Midrand">Midrand</option>')

} else if ($('#country option:selected').text == "USA") {

$('#location').append('<option value="Downers Grove">Downers Grove</option>')

} else if ($('#country option:selected').text == "Mexico") {

$('#location').append('<option value="Puebla">Puebla</option>')

} else if ($('#country option:selected').text == "China") {

$('#location').append('<option value="Beijing">Beijing</option>')

} else if ($('#country option:selected').text == "Spain") {

$('#location').append('<option value="Barcelona">Barcelona</option>')

});

});

HTML
<label class="page1">Country</label>

<div class="tooltips" title="Please select the country that the customer will primarily be served
from">

<select id="country" name="country" onchange="populate(this.id,'location')"


placeholder="Phantasyland">

<option></option>

<option>Germany</option>

<option>Spain</option>

<option>Hungary</option>

<option>USA</option>

<option>Mexico</option>

<option>South Africa</option>

<option>China</option>

<option>Russia</option>

</select>

</div>

<br />

<br />

<label class="page1">Location</label>

<div class="tooltips" title="Please select the city that the customer is primarily to be served
from.">

<select id="location" name="location" placeholder="Anycity"></select>

</div>
jQuery(function($) {
var locations = {
'Germany': ['Duesseldorf', 'Leinfelden-Echterdingen', 'Eschborn'],
'Spain': ['Barcelona'],
'Hungary': ['Pecs'],
'USA': ['Downers Grove'],
'Mexico': ['Puebla'],
'South Africa': ['Midrand'],
'China': ['Beijing'],
'Russia': ['St. Petersburg'],
}

var $locations = $('#location');


$('#country').change(function () {
var country = $(this).val(), lcns = locations[country] || [];

var html = $.map(lcns, function(lcn){


return '<option value="' + lcn + '">' + lcn + '</option>'
}).join('');
$locations.html(html)
});
});

<select class="select" id="province" onchange="filterCity();">


<option value="1">RM</option>
<option value="2">FI</option>
</select>

<select class="select" id="city" disabled>


<option data-province="RM" value="1">ROMA</option>
<option data-province="RM" value="2">ANGUILLARA SABAZIA</option>
<option data-province="FI" value="3">FIRENZE</option>
<option data-province="FI" value="4">PONTASSIEVE</option>
</select>

this one is not visible, and acts as a container for all the elements filtered out by the
selection:

<span id="option-container" style="visibility: hidden; position:absolute;"></span>

<script>

function filterCity(){
var province = $("#province").find('option:selected').text(); // stores province
$("#option-container").children().appendTo("#city"); // moves <option> contained in #option-
container back to their <select>
var toMove = $("#city").children("[data-province!='"+province+"']"); // selects city elements to move
out
toMove.appendTo("#option-container"); // moves city elements in #option-container
$("#city").removeAttr("disabled"); // enables select
};
</script>
I have created cascading Dropdown for Country, State, City and Zip. It may helpful to someone.
Here only some portion of code are posted you can see full working example on jsfiddle

//Get html elements


var countySel = document.getElementById("countySel");
var stateSel = document.getElementById("stateSel");
var citySel = document.getElementById("citySel");
var zipSel = document.getElementById("zipSel");

//Load countries
for (var country in countryStateInfo) {
countySel.options[countySel.options.length] = new Option(country, country);
}

//County Changed
countySel.onchange = function () {

stateSel.length = 1; // remove all options bar first


citySel.length = 1; // remove all options bar first
zipSel.length = 1; // remove all options bar first

if (this.selectedIndex < 1)
return; // done

for (var state in countryStateInfo[this.value]) {


stateSel.options[stateSel.options.length] = new Option(state, state);
}
}

$(document).ready(function(){

var ListNiveauCycle = [{"idNiveau":1,"libelleNiveau":"CL1","idCycle":1},


{"idNiveau":26,"libelleNiveau":"Niveau 22","idCycle":24},
{"idNiveau":34,"libelleNiveau":"CL3","idCycle":1},
{"idNiveau":35,"libelleNiveau":"DAlf3","idCycle":1}];
console.log(ListNiveauCycle);

function remplirListNiveau(idCycle){
console.log('remplirListNiveau');
var $niveauSelect = $("#niveau");
// vider la liste
$niveauSelect.empty();
for (var i = 0; i < ListNiveauCycle.length; i++) {

if(ListNiveauCycle[i].idCycle==idCycle){
var opt1 = document.createElement('option');
opt1.innerHTML = ListNiveauCycle[i].libelleNiveau;
opt1.value = ListNiveauCycle[i].idNiveau;
$niveauSelect.append(opt1);
}
}
}

$("#cycles").change(function(){
remplirListNiveau(this.value)
});

});
SELECT 1

1. &#60;form name=&#34;f1&#34;&#62;
2. &#60;select name=pais onchange=&#34;cambia_provincia()&#34;&#62;
3. &#60;option value=&#34;0&#34; selected&#62;Seleccione...
4. &#60;option value=&#34;1&#34;&#62;España
5. &#60;option value=&#34;2&#34;&#62;Argentina
6. &#60;option value=&#34;3&#34;&#62;Colombia
7. &#60;option value=&#34;4&#34;&#62;Francia
8. &#60;/select&#62;
9.  
10. &#60;select name=provincia&#62;
11. &#60;option value=&#34;-&#34;&#62;-
12. &#60;/select&#62;
13. &#60;/form&#62;
14.  

SELECT 2

ARRAYS

1. var provincias_1=new Array(&#34;-


&#34;,&#34;Andalucía&#34;,&#34;Asturias&#34;,&#34;Baleares&#34;,
&#34;Canarias&#34;,&#34;Castilla y León&#34;,&#34;Castilla-La
Mancha&#34;,&#34;...&#34;)
2. var provincias_2=new Array(&#34;-&#34;,&#34;Salta&#34;,&#34;San
Juan&#34;,&#34;San Luis&#34;,&#34;La Rioja&#34;,&#34;La
Pampa&#34;,&#34;...&#34;)
3. var provincias_3=new Array(&#34;-
&#34;,&#34;Cali&#34;,&#34;Santamarta&#34;,&#34;Medellin&#34;,&#3
4;Cartagena&#34;,&#34;...&#34;)
4. var provincias_4=new Array(&#34;-
&#34;,&#34;Aisne&#34;,&#34;Creuse&#34;,&#34;Dordogne&#34;,&#34;E
ssonne&#34;,&#34;Gironde &#34;,&#34;...&#34;)
5.  
CREAMOS DEPENDENCIA

1. function cambia_provincia(){
2.     var pais
3.     pais =
document.f1.pais[document.f1.pais.selectedIndex].value
4.     if (pais != 0) {
5.       mis_provincias=eval(&#34;provincias_&#34; + pais)
6.        num_provincias = mis_provincias.length
7.        document.f1.provincia.length = num_provincias
8.         for(i=0;i&#60;num_provincias;i++){
9.          
document.f1.provincia.options[i].value=mis_provincias[i]
10.          
document.f1.provincia.options[i].text=mis_provincias[i]
11.        }
12.     }else{
13.        document.f1.provincia.length = 1
14.        document.f1.provincia.options[0].value = &#34;-&#34;
15.        document.f1.provincia.options[0].text = &#34;-&#34;
16.     }
17.     document.f1.provincia.options[0].selected = true
18. }
19.  
20.  

CONSULTA A BBDD

1. &#60;?php
2. while(&#036;row = mysql_fetch_array(&#036;result)) {
3. echo &#34;&#60;option
value=&#34;.&#036;row[&#34;valor&#34;].&#34;&#62;&#34;.&#036;row
[&#34;enunciado&#34;].&#34;&#60;/option&#62;&#34;; }
4. ?&#62;
PASAR LA CONSULTA PHP A JAVASCRIPT

1. &#60;?php
2. &#036;javascript = &#34;&#60;script
language=&#092;&#34;JavaScript&#092;&#34;&#62;&#092;n&#34;;
3. &#036;javascript .= &#34;   var array_js = new
Array();&#092;n&#34;;
4. //aqui nos conectariamos a la base de datos,,, a tu gusto!!!!!
Yo uso algo asi:
5. include(&#34;conexion_bd.php&#34;);
6. &#036;link=Conexion();
7. &#036;valores=mysql_query(&#34;select * from
columna&#34;,&#036;link) or die (mysql_error());
8.  
9. &#036;contador = 0;
10. while (&#036;elem = mysql_fetch_array(&#036;valores)) {
11.  
&#036;javascript .=&#34;columna[&#34;.&#036;contador.&#34;] =
&#34;.&#036;elem['columna2'].&#34;;&#092;n&#34;;  
12.   &#036;contador++;                                  }
13. &#036;javascript .= &#34;&#60;/script&#62;&#092;n&#34;;
14. echo &#036;javascript;
15. ?&#62;
16.  

https://solocodigo.com/9550/menu-desplegable-de-paises-y-ciudades/
Here is what I did :

Step 1:
Fill the first field. I posted a method on how to do that on this post or th that post(in french)

Step 2:
-Download this (Right click : save target as ff_XHConn.js)
-Open it and change the class name to ff_XHConn
-Place it in your template folder (in my case it's located in :\templates\siteground-j15-186)
-Then edit the file index.php of your template and add betwenn <head> and </head> this line :

<script type="text/javascript" src="ff_XHConn.js"></script>

Step 3:
Create a PHP file and place it into a new folder that you created in joomla's folder
As for me, I created a folder named "hierselect" and a file named "requetes.php" (You will see it
appear on the code of the step4 like this : /hierselect/requetes.php)

The PHP code that works for me is the following :

<?php

$field1=$_GET['field1']; //CHANGE FIELD 1 TO THE VALUE OF YOUR 1ST


FIELD

mysql_connect("127.0.0.1","root",""); //ADAPT TO YOUR SERVER

mysql_select_db("PAT"); //CHANGE "PAT" TO THE NAME OF YOUR DATABASE

$lien2='Select * from TabMais6 where col1=\''.$field1.'\'' ; //CHANGE


TO YOUR REQUEST

$image2=mysql_query($lien2) or die (mysql_error());

while($uneligne2=mysql_fetch_assoc($image2))

$test2 .= "<option
value=\"{$uneligne2['id']}\">{$uneligne2['col2']}</option>\n";

//IN THE PREVIOUS LINE CHANGE id AND col2 TO ATTRIBUTES OF YOUR


DATABASE

echo $test2;

?>

Just change what's said in the code above


Step 4 Adapt the following actionscript piece of code to your case.
Change field1 to the name of your first list
Change field2 to the name of your second list
Change "/hierselect/requetes.php" to the name of the folder and file you created in step 3

function ff_field1_action(element, action)

var myConn = new ff_XHConn();

if (!myConn) {alert("XMLHTTP not available. Try a newer/better


browser.");}

var fnWhenDone = function (oXML)

ff_getElementByName('field2').innerHTML = oXML.responseText;

ff_getElementByName('field2').disabled=false;

};

ff_getElementByName('field2').disabled=true;

ff_getElementByName('field2').value = '';

myConn.connect("/hierselect/requetes.php", "GET",
"field1="+ff_getElementByName('field1').value, fnWhenDone);

Place this code in the your first field (not in the 2nd!) there :


=>advanced tab=> section "Active Script"(or something like that)=> click "custom"=> click
"change"=> place the code=>save !

https://crosstec.org/en/forums/3-breezingforms-general-forum-english/6417-how-change-
values-to-select-list.html?limit=6&start=12#32087

https://github.com/junioryauricasa/DropDown-Ubigeo
https://desarrolloweb.com/articulos/1281.php

<form name="f1">
<select name=pais onchange="cambia_provincia()">
<option value="0" selected>Seleccione...
<option value="1">España
<option value="2">Argentina
<option value="3">Colombia
<option value="4">Francia
</select>

<select name=provincia>
<option value="-">-
</select>
</form>

var provincias_1=new
Array("-","Andalucía","Asturias","Baleares","Canarias","Castilla
y León","Castilla-La Mancha","...")
var provincias_2=new Array("-","Salta","San Juan","San Luis","La
Rioja","La Pampa","...")
var provincias_3=new
Array("-","Cali","Santamarta","Medellin","Cartagena","...")
var provincias_4=new
Array("-","Aisne","Creuse","Dordogne","Essonne","Gironde
","...")

Podemos combinar los arrays en uno solo, con este literal de array.

var todasProvincias = [
[],
provincias_1,
provincias_2,
provincias_3,
provincias_4,
];

 Detecto el país que se ha seleccionado


 Si el valor del país no es 0 (el valor 0 es cuando no se ha seleccionado
país)
o Tomo el array de provincias adecuado, utilizando el índice del
país.
o Marco el número de opciones que debe tener el select de
provincias
o Para cada opcion del select, coloco su valor y texto asociado,
que se hace corresponder con lo indicado en el array de
provincias.
 SI NO (El valor de país es 0, no se ha seleccionado país)
o Coloco en el select de provincia un único option con el valor "-",
que significaba que no había provincia.
 Coloco la opción primera del select de provincia como la seleccionada.

function cambia_provincia(){
//tomo el valor del select del pais elegido
var pais
pais =
document.f1.pais[document.f1.pais.selectedIndex].value
//miro a ver si el pais está definido
if (pais != 0) {
//si estaba definido, entonces coloco las opciones de la
provincia correspondiente.
//selecciono el array de provincia adecuado
mis_provincias=todasProvincias[pais]
//calculo el numero de provincias
num_provincias = mis_provincias.length
//marco el número de provincias en el select
document.f1.provincia.length = num_provincias
//para cada provincia del array, la introduzco en el
select
for(i=0;i<num_provincias;i++){

document.f1.provincia.options[i].value=mis_provincias[i]

document.f1.provincia.options[i].text=mis_provincias[i]
}
}else{
//si no había provincia seleccionada, elimino las
provincias del select
document.f1.provincia.length = 1
//coloco un guión en la única opción que he dejado
document.f1.provincia.options[0].value = "-"
document.f1.provincia.options[0].text = "-"
}
//marco como seleccionada la opción primera de provincia
document.f1.provincia.options[0].selected = true
Código completo de los selects dependientes

Para que te sea más sencillo de comprobar el funcionamiento de este ejemplo


y reproducir los pasos para llegar a poner en marcha el ejercicio de los selects
dependientes, te pasamos ahora el código completo.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>

<form name="f1">
<select name=pais onchange="cambia_provincia()">
<option value="0" selected>Seleccione...
<option value="1">España
<option value="2">Argentina
<option value="3">Colombia
<option value="4">Francia
</select>

<select name=provincia>
<option value="-">-
</select>
</form>

<script>
var provincias_1=new
Array("-","Andalucía","Asturias","Baleares","Canarias","Castilla
y León","Castilla-La Mancha","...");
var provincias_2=new Array("-","Salta","San Juan","San
Luis","La Rioja","La Pampa","...");
var provincias_3=new
Array("-","Cali","Santamarta","Medellin","Cartagena","...");
var provincias_4=new
Array("-","Aisne","Creuse","Dordogne","Essonne","Gironde
","...");

var todasProvincias = [
[],
provincias_1,
provincias_2,
provincias_3,
provincias_4,
];

function cambia_provincia(){
//tomo el valor del select del pais elegido
var pais
pais =
document.f1.pais[document.f1.pais.selectedIndex].value
//miro a ver si el pais está definido
if (pais != 0) {
//si estaba definido, entonces coloco las opciones de la
provincia correspondiente.
//selecciono el array de provincia adecuado
mis_provincias=todasProvincias[pais]
//calculo el numero de provincias
num_provincias = mis_provincias.length
//marco el número de provincias en el select
document.f1.provincia.length = num_provincias
//para cada provincia del array, la introduzco en el
select
for(i=0;i<num_provincias;i++){

document.f1.provincia.options[i].value=mis_provincias[i]

document.f1.provincia.options[i].text=mis_provincias[i]
}
}else{
//si no había provincia seleccionada, elimino las
provincias del select
document.f1.provincia.length = 1
//coloco un guión en la única opción que he dejado
document.f1.provincia.options[0].value = "-"
document.f1.provincia.options[0].text = "-"
}
//marco como seleccionada la opción primera de provincia
document.f1.provincia.options[0].selected = true
}

</script>
</body>
</html>

You might also like