How to populate a cascading Dropdown with JQuery - javascript

i have the following problem:
I started to create a form with HTML an JS and there are two Dropdowns (Country and City). now i want to make these two dynamic with JQuery so that only the cities of the selected countries are visible.
I've started with some basic JS which worked fine but makes some trouble in IE. Now i'm trying to convert my JS to JQuery for a better compatibility.
My original JS looks like this:
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);
}
};
and here my Jquery:
http://jsfiddle.net/HvXSz/
i know it is very simple but i can't see the wood for the trees.

It should as simple as
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)
});
});
Demo: Fiddle

I'm going to provide a second solution, as this post is still up in Google search for 'jquery cascade select'.
This is the first select:
<select class="select" id="province" onchange="filterCity();">
<option value="1">RM</option>
<option value="2">FI</option>
</select>
and this is the second, disabled until the first is selected:
<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>
Finally, the script that filters:
<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);
}
}
Fiddle Demo

I have a handy code. you can just copy it:
Same as above
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
jQuery(function($) {
var locations = {
'Germany': ['Duesseldorf', 'Leinfelden-Echterdingen', 'Eschborn', 'asdasdasd'],
'Spain': ['Barcelona'],
'Hungary': ['Pecs'],
'USA': ['Downers Grove'],
'Mexico': ['Puebla'],
'South Africa': ['Midrand'],
'China': ['Beijing'],
'Japn': ['tokyo'],
'Shuidong': ['shuidongjie','maomingjie'],
'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)
});
});
</script>
</head>
<body>1
<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" 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>Japn</option>
<option>Shuidong</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>
</body>
</html>

This is an example that I've done. I wish that will be useful for you.
$(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)
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group row">
<label class="col-sm-3 col-form-label">Cycle</label>
<div class="col-sm-9">
<select class="form-control" id="cycles" required="">
<option value="">-----------</option>
<option value="1">Cycle1</option>
<option value="24">Cycle2</option>
</select>
</div>
</div>
<div class="col-md-4">
<div class="form-group row">
<label class="col-sm-3 col-form-label">Niveau</label>
<div class="col-sm-9">
<select id="niveau" class="form-control" required="" name="niveau.id">
</select>
</div>
</div>
</div>

Related

JavaScript onchange event for dynamic dropdown in HTML

I am not sure if I am wording this correctly. I have a dropdown menu, that when an option is selected, the second dropdown pops in and has options for the selected value. This all works great, but now I am trying to give a button to add more dropdowns in JavaScript. The first works, but I cannot get the second value to show.
HTML code:
<table class="table-container">
<tbody><tr><td>
<select class="custom-select" id="mediaSel" name="mediaSel" onchange="dropDownSelect(this.id, 'mediaSel2')">
<option value="">--Select--</option>
<option value="Illustration" name="Illustration">Illustration</option>
<option value="GraphicDesign" name="GraphicDesign">Graphic Design</option>
<option value="MotionGraphics" name="MotionGraphics">Motion Graphics</option>
<option value="WebDesign" name="WebDesign">Web Design</option>
</select>
</td><td>
<select class="custom-select" id="mediaSel2" name="mediaSel2"></select>
</td><td class="buttonRow">
<div id="addRow" class="addButton" onclick="addSelection()"><span class="plus"></span></div>
</td></tr></tbody>
</table>
So from here I was able to add the second dropdown when the onchange event has been fired.
JS code:
function dropDownSelect(s1,s2) {
var s1 = document.getElementById(s1);
var s2 = document.getElementById(s2);
var hideSel = document.getElementById("mediaSel2");
s2.innerHTML = "";
if(s1.value == "Illustration") {
var optionArray = ["Select|--select--","ChildrensBooks|Childrens Book Design","FanArt|Fan Art","WallArt|Wall Art"];
}
else if(s1.value == "GraphicDesign") {
var optionArray = ["Select|--select--","Logo|Logo","BusinessCards|Business Cards","Flyers|Flyers","Billboards|Billboards","MagazineAds|Magazine Ads","CatalogeDesign|Cataloge Design","NewsPaperAds|Newspaper Ads"];
}
else if(s1.value == "MotionGraphics") {
var optionArray = ["Select|--select--","LogoAnimation|Logo Animation","Explainers|Explainer Videos","ShortFilms|Short Film Animation","CharacterDesign|Character Design","ProductDesign|Product Design","Animation|Animation"];
}
else if(s1.value == "WebDesign") {
var optionArray = ["Websites|Websites"];
}
if(s1.value == "GraphicDesign" || s1.value == "Illustration" || s1.value == "MotionGraphics" || s1.value == "WebDesign") {
s2.style.display="inline-block";
} else {
s2.style.display="none";
}
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);
}
}
Like I said this all works great. but the final step is where I am struggling. I have the addButton in HTM that when clicked runs the next js code and gives me the dropdown.
I can't seem to figure out how to attach the function dropDownSelect from above.
addButton JS:
function addSelection() {
var html = '<tr><td><select class="custom-select addClick" id="mediaSel" name="mediaSel" onchange="dropDownSelect2(this.id, "mediaSel2")"><option value="">--Select--</option><option value="Illustration" name="Illustration">Illustration</option><option value="GraphicDesign" name="GraphicDesign">Graphic Design</option><option value="MotionGraphics" name="MotionGraphics">Motion Graphics</option><option value="WebDesign" name="WebDesign">Web Design</option></select></td><td><select class="custom-select" id="mediaSel2" name="mediaSel2"></select></td><td class="buttonRow"><div id="removeRow" class="removeButton" onclick="removeSelection()"><span class="minus"></span></div></td></tr>';
$('tbody').append(html);
}
any thoughts?
You need to escape the inner pair of double quotes around the parameter of the function call:
var html = '... onchange="dropDownSelect2(this.id, \"mediaSel2\")"><option ...`;

How do I get a value from another page and output it to a selectlist? JAVASCRIPT

I have several input elements in which I enter the name of the book author and the book title. This data should appear in a selectlist that is on a different page. I have to pass values from one page to another, but I don't know how to do it in JavaScript. Could you show me how to do it?
HTML
<div class="child">
<input id="item" type="text" placeholder="Add book" required>
<input id="item2" type="text" placeholder="Add author" required>
<select id="mySelect" class="block">
<option>JS Part 1</option>
<option>JS Part 2</option>
<option>HTML + CSS book</option>
<option>Bootstrap</option>
</select>
<select id="mySelect2" class="block">
<option>Author 1</option>
<option>Author 2</option>
<option>Author 3</option>
<option>Author 4</option>
</select>
<input type="submit" id="send" class="block">
</div>
JS
var inp = document.getElementById("item");
inp.value = "Book Title";
var inp2 = document.getElementById("item2");
inp2.value = "Author name";
var itemsArray = localStorage.getItem('items') ?
JSON.parse(localStorage.getItem('items')) : [];
send.onclick = function (e) {
e.preventDefault();
let name = {
obj: "ID: ",
obj2: " Book: ",
obj3: " Author: "
}
var li = document.getElementsByClassName("me");
var count = li.length;
console.log(count);
var sel = document.getElementById('mySelect').selectedIndex;
var options = document.getElementById('mySelect').options;
var sel2 = document.getElementById('mySelect2').selectedIndex;
var options2 = document.getElementById('mySelect2').options;
var string = name.obj + (count + 1) + " | " + name.obj2 + inp.value + " | " + name.obj3 + inp2.value;
itemsArray.push(string);
localStorage.setItem('items', JSON.stringify(itemsArray));
}
on submit add data in localstorage
var itemsArray = localStorage.getItem('items') ?
JSON.parse(localStorage.getItem('items')) : {authors:[],books:[]};
itemsArray.authors.push(inp);
itemsArray.books.push(inp2);
then on next page you can do is
document.addEventListener("DOMContentLoaded", function(event)
{
console.log("DOM fully loaded ");
let data=JSON.parse(localstorage.getItem('items'))
let select1="";
data.authors.map(author=>{
select1+="<option>"+author+"</option>"
})
//populate in input fields accordingly
document.getElementById("slect1").innerHTML=select1 //same way you can do this for book also
}

remove input with javascript

I have a problem at javascript code level, in fact I want when I choose option = apartment it shows me 3 input text and if I click after option = home it removes the 3 input text.
But my code does not remove the 3 input if I chose house.
document.getElementById('contrat').onchange = function() {
if (this.value == 'appartement') {
console.log('appartement');
var new_input1 = document.createElement('input');
var new_input2 = document.createElement('input');
var new_input3 = document.createElement('input');
new_input1.type = "text";
new_input1.id = 'ascenseur';
new_input1.name = 'ascenceur';
new_input1.placeholder = 'oui/non';
new_input1.setAttribute("class", "form-control");
new_input2.type = "text";
new_input2.id = 'code';
new_input2.name = 'code';
new_input2.placeholder = 'code/interphone';
new_input2.setAttribute("class", "form-control");
new_input3.type = "text";
new_input3.id = 'porte';
new_input3.name = 'porte';
new_input3.placeholder = 'la porte';
new_input3.setAttribute("class", "form-control");
document.getElementById('champ2').innerHTML = "";
document.getElementById('champ3').innerHTML = "";
document.getElementById('champ4').innerHTML = "";
document.getElementById('champ2').appendChild(new_input1);
document.getElementById('champ3').appendChild(new_input2);
document.getElementById('champ4').appendChild(new_input3);
}
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div class="form-group">
<label>Logement* </label>
<select id="contrat" class=form-control name="logement">
<option>--------</option>
<option value="appartement">Appartement</option>
<option value="maison">Maison</option>
<option value="autre">Autre</option>
</select>
</div>
<div class="form-group">
<div id="champ2"></div>
<div id="champ3"></div>
<div id="champ4"></div>
</div>
All you need is to check if its maison
Demo: http://jsfiddle.net/sfr3wb2p/1/
if (this.value == 'maison') {
document.getElementById('champ2').innerHTML = "";
document.getElementById('champ3').innerHTML = "";
document.getElementById('champ4').innerHTML = "";
}
Make an extra if $(this).val() === 'maison' to empty when this option is selected. Also changed your plain Javascript code to jQuery to show you how this is done since you tagged your question with jQuery.
As said in the comments, you might want to consider to just hide and show the elements. This way the value of the input is not lost when changing the select.
$('#contrat').on('change', function() {
if ($(this).val() === 'appartement') {
console.log('appartement');
var $new_input1 = $('<input>');
var $new_input2 = $('<input>');
var $new_input3 = $('<input>');
$new_input1.attr('type', 'text')
.attr('type', 'ascenseur')
.attr('name', 'ascenceur')
.attr('placeholder', 'oui/non')
.attr("class", "form-control");
$new_input2.attr('type', 'text')
.attr('type', 'code')
.attr('name', 'code')
.attr('placeholder', 'code/interphone')
.attr("class", "form-control");
$new_input3.attr('type', 'text')
.attr('type', 'porte')
.attr('name', 'porte')
.attr('placeholder', 'la porte')
.attr("class", "form-control");
$('#champ2').empty();
$('#champ3').empty();
$('#champ4').empty();
$('#champ2').append($new_input1);
$('#champ3').append($new_input2);
$('#champ4').append($new_input3);
}
else if($(this).val() === 'maison') {
console.log('maison');
$('#champ2').empty();
$('#champ3').empty();
$('#champ4').empty();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div class="form-group">
<label>Logement* </label>
<select id="contrat" class=form-control name="logement">
<option>--------</option>
<option value="appartement">Appartement</option>
<option value="maison">Maison</option>
<option value="autre">Autre</option>
</select>
</div>
<div class="form-group">
<div id="champ2"></div>
<div id="champ3"></div>
<div id="champ4"></div>
</div>

Javascript onchange event not working in my code

what is wrong with this code? Why is my onchange event not working? I have tried a lot already and it's making me nuts. Please help?
<!DOCTYPE html>
<html>
<head>
<script type=text/javascript>
function populate(s1,s2){
var s1 = document.getElementById(s1);
var s2 = document.getElementById(s2);
s2.innerHTML = "";
if(s1.value == "Chevy"){
var optionArray ["|", "camaro|Camaro", "corvette|Corvette",
"impala|Impala"];
}
else if(s1.value=="Dodge"){
var optionArray=["|", "avanger|Avanger", "challenger|Challenger",
"charger|Charger"];
}
else if(s1.value=="Ford"){
var optionArray=["|", "mustang|Mustang", "shelby|Shelby"];
}
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);
}
}
</script>
</head>
<body>
<h2>Choose Your Car</h2>
<hr />
Choose Car Make:
<select id="slct1" name="slct1" onchange="populate(this.id, 'slct2')">
<option value="">Select</option>
<option value="Chevy">Chevy</option>
<option value="Dodge">Dodge</option>
<option value="Ford">Ford</option>
</select>
<hr />
Choose Car Model:
<select id="slct2" name="slct2"></select>
<hr />
</body>
</html>
Anyone, please point out to me where is the exact problem...Let me try running it accordingly
Two changes. Change innerHtml to innerHTML and assign an = sign in
if(s1.value == "Chevy"){
var optionArray ["|", "camaro|Camaro", "corvette|Corvette",
"impala|Impala"];
}
correct the above to
if(s1.value == "Chevy"){
var optionArray = ["|", "camaro|Camaro", "corvette|Corvette",
"impala|Impala"];
}
JSFIDDLE
Try the following:
<select id="slct1" name="slct1" onchange="populate(this, 'slct2')">
js:
populate = function(s1,s2) {
var s2 = document.getElementById(s2);
s2.innerHTML = "";
if(s1.value == "Chevy"){
var optionArray = ["|", "camaro|Camaro", "corvette|Corvette",
"impala|Impala"];
}
else if(s1.value=="Dodge"){
var optionArray=["|", "avanger|Avanger", "challenger|Challenger",
"charger|Charger"];
}
else if(s1.value=="Ford"){
var optionArray=["|", "mustang|Mustang", "shelby|Shelby"];
}
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);
}
}
demo:
https://jsfiddle.net/xkyffr4h/1/

How to create a select that depends on the value of another select?

I need to create a menu of regions hat display two lists: a <select> for the region and another <select> for the available municipalities of that region. For this, I have a <form> and I update the municipalities through JavaScript. I have problems assigning the municipalities as <option>s of the second <select>. The option matrix of the menu doesn't accept the assignment of the values.
Here's the code.
HTML.
<html>
<head>
<title>
Página menú principal.
</title>
<?!= incluirArchivo('ArchivoJS'); ?>
</head>
<body onLoad = "preparar();">
<form id="formularioConductor" name="formularioConductor" method="post" enctype="multipart/form-data" autocomplete = "on">
<select name="menuDepartamento" id="menuDepartamento" tabindex="2" accesskey="e" onChange="municipiosDepartamento();">
<option value="x" selected="selected">ELIJA UN DEPARTAMENTO</option>
<option value="0">Antioquia</option>
<option value="1">Atlántico</option>
</select>
<select name="menuMunicipios" id="menuMunicipios" tabindex="3" disabled>
<option value=0>TODOS LOS MUNICIPIOS</option>
</select>
</form>
</body>
</html>
Javascript code:
<script lenguage="javascript">
function preparar() {
document.forms[0].elements.numeroLicencia.focus();
document.forms[0].elements.nombreConductor.disabled = true;
document.forms[0].elements.botonEnviar.disabled = true;
document.forms[0].elements.botonActualizar.disabled = true;
}
function municipiosDepartamento() {
var arregloMunicipiosDepartamento = new Array();
var posicionMunicipio = document.forms[0].elements.menuDepartamento.value;
arregloMunicipiosDepartamento = municipiosColombia(posicionMunicipio);
if(document.forms[0].elements.menuMunicipios.options.length > 1){
var totalMunicipios = document.forms[0].elements.menuMunicipios.length;
for (var i = 1; i < totalMunicipios; i ++){
document.forms[0].elements.menuMunicipios.options[1] = null;
}
}
if(document.forms[0].elements.menuDepartamento.value === "x"){
document.forms[0].elements.menuMunicipios.selectedItem = 0;
document.forms[0].elements.menuMunicipios.disabled = true;
}
else
{
document.forms[0].elements.menuMunicipios.options.length = arregloMunicipiosDepartamento.length;
for (var i = 0; i < arregloMunicipiosDepartamento.length; i ++) {
var opcionTemporal = new Option(arregloMunicipiosDepartamento[i], (i+1));
***document.forms[0].elements.menuMunicipios.options[i+1].text = opcionTemporal.text;
document.forms[0].elements.menuMunicipios.options[i+1].value = opcionTemporal.value;***
}
document.forms[0].elements.menuMunicipios.disabled = false;
}
}
function municipiosColombia(posicion) {
var antioquia, atlantico, arregloTodos, arregloMunicipiosDepartamento = new Array();
antioquia=["Medellín","Abejorral","Abriaqui","Alejandria"];
atlantico = ["Barranquilla","Baranoa","Campo De La Cruz","Candelaria"];
arregloTodos = [antioquia, atlantico];
arregloMunicipiosDepartamento=arregloTodos[posicion];
return arregloMunicipiosDepartamento;
}
</script>
I have highlighted the work that doesn't work.
The way I would do what you describe is to clear out the options each time and recreate the required ones, then add them into the particular select, like so:
var regions = {};
regions['A'] = ['mu', 'ni', 'ci', 'pal', 'it', 'y'];
regions['B'] = ['I', 'like', 'bananas'];
var selRegion = document.getElementById('region');
selRegion.onchange = setMunicipalities;
var selMun = document.getElementById('municipality');
function setMunicipalities(e)
{
while(selMun.length > 0)
{
selMun.remove(0);
}
if(selRegion.selectedOptions[0].value === 'ALL')
{
for(var r in regions)
{
if(regions.hasOwnProperty(r))
{
addMunicipalities(regions[r]);
}
}
}
else
{
var reg = selRegion.selectedOptions[0].value;
addMunicipalities(regions[reg]);
}
}
function addMunicipalities(region)
{
var allMun = document.createElement('option');
allMun.setAttribute('value', 'ALL');
var allMunText = document.createTextNode('ALL');
allMun.appendChild(allMunText);
selMun.add(allMun);
for (var mi = 0; mi < region.length; mi++)
{
var m = region[mi];
var mun = document.createElement('option');
mun.setAttribute('value', m);
var munText = document.createTextNode(m);
mun.appendChild(munText);
selMun.add(mun);
}
}
setMunicipalities(null);
<label for="region">Region</label>
<select id="region">
<option selected="selected" value="ALL">ALL</option>
<option value="A">A</option>
<option value="B">B</option>
</select>
<label for="municipality">Municipality</label>
<select id="municipality">
</select>
I haven't read your entire code because I had a hard time reading code with contents not in English but anyway, I get what you're trying to do here. Suppose that your first select list contains "Region A" and "Region B" as options; "Municipality A1", "Municipality A2", "Municipality B1","Municipality B2" are the possible options for the second select list. Here's a function that will change the options of the second select list depending on what is selected on the first select list:
function optionChanger(v_selected){
var whatisselected= v_selected.options[v_selected.selectedIndex].value;
var municipalities= {};
municipalities['A'] = ['Municipality A1','Municipality A2'];
municipalities['B'] = ['Municipality B1','Municipality B2'];
v_selected.options.length=0; //remove the contents of the second select list
v_selected.options[0] = new Option(municipalities[whatisselected][0],municipalities[whatisselected][0],false,true);// set the first option of the second list as the default selected value
for(x=1;x<municipalities[whatisselected].length;x++){ //add the remaining options to the second list
v_selected.options[x] = new Option(municipalities[whatisselected][x],municipalities[whatisselected][x],false,false);
}
}
Then add this inside the tag of your FIRST select list:
onchange='optionChanger(this)'
PS: Please notice that the return value of the first select list must be 'A', 'B'

Categories