I am not able to design the function "print_district" to get the values from s_b.
Kindly help me to defined this multidimensional array.
I suppose to get c11,c12,c13,... on selection from C1 from country country 1 and c21,c22,c23,... on selecting C2 from country 1
But I am getting d11,d12,d13,... and d12,d22,23 so on which is from country 2
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<script type= "text/javascript">
var country_arr = new Array("country 1", "country 2");
var s_a = new Array();
s_a[0]="";
s_a[1]="C1|C2";
s_a[2]="D1|D2";
var s_b = new Array();
s_b[1,1]="c11|c12|c13|c14|c15|c16|c17|c18|c19|c10";
s_b[1,2]="c21|c22|c23|c24|c25|c26|c27|c28|c29|c210";
s_b[2,1]="d11|d12|d13|d14|d15|d16|d17|d18|d19|d10";
s_b[2,2]="d21|d22|d23|d24|d25|d26|d27|d28|d29|d210";
function print_country(country_id){
// given the id of the <select> tag as function argument, it inserts <option> tags
var option_str = document.getElementById(country_id);
option_str.length=0;
option_str.options[0] = new Option('Select Country','');
option_str.selectedIndex = 0;
for (var i=0; i<country_arr.length; i++) {
option_str.options[option_str.length] = new Option(country_arr[i],country_arr[i]);
}
}
function print_state(state_id, state_index){
var option_str = document.getElementById(state_id);
option_str.length=0;
option_str.options[0] = new Option('Select State','');
option_str.selectedIndex = 0;
var state_arr = s_a[state_index].split("|");
for (var i=0; i<state_arr.length; i++) {
option_str.options[option_str.length] = new Option(state_arr[i],state_arr[i]);
}
}
//This function is incorrect, just to demonstrate, please help to correct this
function print_district(district_id, district_index){
var option_str = document.getElementById(district_id);
option_str.length=0;
option_str.options[0] = new Option('Select district','');
option_str.selectedIndex = 0;
var district_arr = s_b[district_index].split("|");
for (var i=0; i<district_arr.length; i++) {
option_str.options[option_str.length] = new Option(district_arr[i],district_arr[i]);
}
}
</script>
</head>
<body>
<form>
Select Country: <select onchange="print_state('state',this.selectedIndex);" id="country" name ="country" ></select>
<br />
State: <select onchange="print_district('district',this.selectedIndex);" name ="state" id ="state"></select>
<br />
District <select name ="district" id ="district"></select>
<input type="submit"></form>
<script language="javascript">print_country("country");</script>
</body>
</html>
Thanks in advance !
This is the solution to the above problem
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<script>
var stateObject = {
"Country 1": {
"C1": ["c11", "c12"],
"C2": ["c21", "c22"]
},
"Country 2": {
"D1": ["d11", "d12"],
"D2": ["d21", "d22"]
}
}
window.onload = function () {
var countySel = document.getElementById("countySel"),
stateSel = document.getElementById("stateSel"),
districtSel = document.getElementById("districtSel");
for (var country in stateObject) {
countySel.options[countySel.options.length] = new Option(country, country);
}
countySel.onchange = function () {
stateSel.length = 1; // remove all options bar first
districtSel.length = 1; // remove all options bar first
if (this.selectedIndex < 1) return; // done
for (var state in stateObject[this.value]) {
stateSel.options[stateSel.options.length] = new Option(state, state);
}
}
countySel.onchange(); // reset in case page is reloaded
stateSel.onchange = function () {
districtSel.length = 1; // remove all options bar first
if (this.selectedIndex < 1) return; // done
var district = stateObject[countySel.value][this.value];
for (var i = 0; i < district.length; i++) {
districtSel.options[districtSel.options.length] = new Option(district[i], district[i]);
}
}
}
</script>
</head>
<body>
<form name="myform" id="myForm">
Select Country: <select name="state" id="countySel" size="1">
<option value="" selected="selected">Select Country</option>
</select>
<br>
<br>
Select State: <select name="countrya" id="stateSel" size="1">
<option value="" selected="selected">Please select Country first</option>
</select>
<br>
<br>
Select District: <select name="district" id="districtSel" size="1">
<option value="" selected="selected">Please select State first</option>
</select><br>
<input type="submit">
</form>
</body>
</html>
Angular 5 - based example it's working. To get values use Form builder and form group.
template.html
<div>
<h2>Hello country/ state/ cities </h2>
<select (change)="countryChange($event)" >
<option>Select</option>
<option *ngFor="let c of countries" [ngValue]="c.country">{{ c.country }}</option>
</select>
<select (change)="statesChange($event)">
<option>Select</option>
<option *ngFor='let state of states' [ngValue]="state.name">{{ state.name }}</option>
</select>
<select >
<option>Select</option>
<option *ngFor='let city of cities' [ngValue]="city">{{ city }}</option>
</select>
</div>
component.ts
countries= [{
"country": "Afghanistan",
"states": [
{ "name":"Nurestan", "cities":["c1", "c2", "c3"] },
{ "name":"Oruzgan", "cities":["orc1", "oruc2", "oruc3"] },
{ "name":"Panjshir", "cities":["3c1", "3c2", "3c3"] }
]
},
{
"country": "Albania",
"states": [
{ "name": "Korce" , "cities":["c1", "c2", "c3"] },
{ "name": "Kukes", "cities":["orc1", "oruc2", "oruc3"] },
{ "name": "Lezhe","cities":["orc1", "oruc2", "oruc3"]},
{ "name": "Shkoder", "cities":["orc1", "oruc2", "oruc3"]},
{ "name": "Tirane","cities":["orc1", "oruc2", "oruc3"]}
]
},
{
"country": "Antarctica",
"states": []
}
]
states= []; cities = [];
countryChange(e){
console.log(e.target.value)
this.countries.filter(element => {
if(element.country == e.target.value){
console.log(element.states[0],"first state")
this.states = element.states;
}
});
this.cities = []
}
statesChange(evt){
console.log(evt.target.value,this.states)
this.states.filter( element =>{
if(element.name == evt.target.value){
this.cities = element.cities;
}
})
}
Related
So I am working on a dynamic dropdown menu made of a parent and a child as the following:
parent :
<select id="category_select">
<option value="1">Electronics</option>
<option value="2">Appliances</option>
</select>
Child :
<select id="type_select">
<option value="1">Phones</option>
<option value="1">Tablets</option>
<option value="2">Couch</option>
<option value="2">Refrigerator</option>
<option value="2">Vacuum</option>
</select>
Here is what I am trying to do:
if the selected option has a value of 1 in category_select, then options available in type_select should only have a value of 1 and all other options should disappear.
Here is the JS :
"use strict";
window.onload = function() {
document.getElementById('category_select').addEventListener("change", function() {
function parent_() {
let parent_ = document.getElementById('category_select');
let ParentVal_ = parent_.options[parent_.selectedIndex].value;
return ParentVal_; // return parent_ value
}
function child_() {
//something I cant figure out here ...
}
});
};
How can I display options in the child that only have the same values that the selected option in the parent?
You can do it in following way:
Like I commented earlier you need to have different child values for each parent value and depending on selected parent you can render child options.
var childs = {
Electronics: [
{
label: 'Phone',
value: 1
},
{
label: 'Tablet',
value: 2
}
],
Appliances: [
{
label: 'Refrigerator',
value: 1
},
{
label: 'Couch',
value: 2
},
{
label: 'Vaccum',
value: 3
}
]
}
function handleChange () {
var x = document.getElementById("category_select").value;
var childOptions = childs[x]
var childSelect = document.getElementById('type_select')
childSelect.innerHTML =''
childOptions.forEach(function (option) {
var optionEle = document.createElement('option')
optionEle.value = option.value
optionEle.label = option.label
childSelect.appendChild(optionEle)
})
}
handleChange()
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
Parent:
<select id="category_select" onChange='handleChange()'>
<option value="Electronics">Electronics</option>
<option value="Appliances">Appliances</option>
</select>
<br />
Child:
<select id="type_select"></select>
</body>
</html>
you can try this script unless hidding but you can disable other options
"use strict";
window.onload = function() {
document.getElementById('category_select').addEventListener("change",
function() {
parent_();
});
function parent_() {
let parent_ = document.getElementById('category_select');
let ParentVal_ = parent_.options[parent_.selectedIndex].value;
child_(ParentVal_);
//return ParentVal_; // return parent_ value
}
function child_(ParentVal_) {
let child = document.getElementById('type_select');
for (var i = 0; i < child.options.length; i++) {
if (child.options[i].value == ParentVal_) {
child.options[i].disabled = true;
}
else
{
child.options[i].enabled = true;
}
}
}
};
i do not think it is a good idea to have value="1" in the option when you have to set the actual value for the option. I think we can use display none to hide the value like this
<head>
<style>
.hide {
display: none
}
</style>
</head>
<body>
<select id="category_select">
<option value="1">Electronics</option>
<option value="2">Appliances</option>
</select>
<select id="type_select">
<option value="phones" category="1">Phones</option>
<option value="tablets" category="1">Tablets</option>
<option value="couch" category="2" class="hide">Couch</option>
<option value="refrigerator" category="2" class="hide">Refrigerator</option>
<option value="vacuum" category="2" class="hide">Vacuum</option>
</select>
</body>
<script>
document.getElementById('category_select').addEventListener("change", function() {
var val = this.value;
var options = document.getElementById('type_select').options;
var new_val = null;
for (var i = 0 ; i < options.length; i++) {
if (options[i].attributes["category"].value === val) {
if (!new_val) {
new_val = options[i].value;
}
options[i].classList.remove("hide");
} else {
options[i].classList.add("hide");
}
}
document.getElementById('type_select').value = new_val;
});
</script>
Check out my version on this.
const categorySelectEl = document.querySelector("#category_select");
const typeSelectEl = document.querySelector("#type_select");
categorySelectEl.addEventListener("change", (e) => {
renderSelectTypes(typeSelectEl, e.target.value);
});
function renderSelectTypes(el, selectedCategory) {
const types = [['Phones', 'Tablets'], ['Couch', 'Refrigerator', 'Vacuum']];
const options = types[Number(selectedCategory) - 1].map(item => `<option value="${selectedCategory}"">${item}</option>`)
el.innerHTML = options.join("\n");
}
const currentlySelected = categorySelectEl.options[categorySelectEl.selectedIndex].value;
https://codesandbox.io/s/lpqn3x0zw7
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8">
<title>Switch Statement and Labeled Break</title>
<script>
addEvent(window, ‘load’, initialize);
function initialize()
{
// add an event to the drop down list
addEvent(document.getElementById(’chips’), ‘change’, getPrice);
}
function product(name, price)
{
this.name = name;
this.price = price;
}
var ICs = new Array();
ICs[0] = new product("Septium 900MHz", "$149");
ICs[1] = new product("Septium Pro 1.0GHz", "$249");
ICs[2] = new product("Octium BFD 750MHz", "$329");
var snacks = new Array();
snacks[0] = new product("Rays Potato Chips", "$1.79");
snacks[1] = new product("Cheezey-ettes", "$1.59");
snacks[2] = new product("Tortilla Flats", "$2.29");
// lookup in the ‘table’ the cost associated with the product
function getPrice()
{
var chipName = this.options[this.selectedIndex].text;
var chipType = this.options[this.selectedIndex].value;
var outField = document.getElementById(’cost’);
master:
switch(chipType)
{
case "ICs":
for (var i = 0; i < ICs.length; i++)
{
if (ICs[i].name == chipName)
{
outField.value = ICs[i].price;
break master;
}
}
break;
case "snacks":
for (var i = 0; i < snacks.length; i++)
{
if (snacks[i].name == chipName)
{
outField.value = snacks[i].price;
break master;
}
}
}
break;
default:
outField.value = "Not Found";
}
}
</script>
</head>
<body>
<h1>Switch Statement and Labeled Break</h1>
<p>Select a chip for lookup in the chip price table:</p>
<form id="theForm">
<p>
<label for="chips">Chip:</label>
<select id="chips">
<option></option>
<option value="ICs">Septium 900MHz</option>
<option value="ICs">Septium Pro 1.0GHz</option>
<option value="ICs">Octium BFD 750MHz</option>
<option value="snacks">Rays Potato Chips</option>
<option value="snacks">Cheezey-ettes</option>
<option value="snacks">Tortilla Flats</option>
<option>Poker Chipset</option>
</select>
<label for="cost"> Price:</label>
<input type="text" id="cost" size="10">
</p>
</form>
</body>
</html>
// In the above code snippets I am trying to show the price for selected chip ,but no price is being shown in the input field.I have attached the output screen shot.I have built two arrays with a custom object ,simulating two database tables.
I am also defining one function getPrice for associating the price related to the product.
Thanks in advance
output screenshot
This works.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8">
<title>Switch Statement and Labeled Break</title>
<script>
window.onload = initialize;
function initialize()
{
document.getElementById('chips').addEventListener('change', getPrice);
}
function product(name, price)
{
this.name = name;
this.price = price;
};
var ICs = new Array();
ICs[0] = new product("Septium 900MHz", "$149");
ICs[1] = new product("Septium Pro 1.0GHz", "$249");
ICs[2] = new product("Octium BFD 750MHz", "$329");
var snacks = new Array();
snacks[0] = new product("Rays Potato Chips", "$1.79");
snacks[1] = new product("Cheezey-ettes", "$1.59");
snacks[2] = new product("Tortilla Flats", "$2.29");
function getPrice()
{
var selectelem = document.getElementById("chips"), outField = document.getElementById('cost'), outvalue="";;
var chipName = selectelem.options[selectelem.selectedIndex].text;
var chipType = selectelem.value;
if(!chipType)
{
outField.value = ""; return;
}
switch(chipType)
{
case "ICs":
var arr = ICs.filter(function(item){
return item.name == chipName;
});
outvalue = arr[0].price;
break;
case "snacks":
var arr = snacks.filter(function(item){
return item.name == chipName;
});
outvalue = arr[0].price;
break;
default: outvalue = "Not Found"; break;
}
outField.value = outvalue;
}
</script>
</head>
<body>
<h1>Switch Statement and Labeled Break</h1>
<p>Select a chip for lookup in the chip price table:</p>
<form id="theForm">
<p>
<label for="chips">Chip:</label>
<select id="chips">
<option></option>
<option value="ICs">Septium 900MHz</option>
<option value="ICs">Septium Pro 1.0GHz</option>
<option value="ICs">Octium BFD 750MHz</option>
<option value="snacks">Rays Potato Chips</option>
<option value="snacks">Cheezey-ettes</option>
<option value="snacks">Tortilla Flats</option>
<option value="signals">TCP</option>
<option value="computer">Poker Chipset</option>
</select>
<label for="cost"> Price:</label>
<input type="text" id="cost" size="10">
</p> </form>
</body>
</html>
The switch is wrong. Should be something like this:
switch (chipType) {
case "ICs":
for (var i = 0; i < ICs.length; i++) {
if (ICs[i].name == chipName) {
outField.value = ICs[i].price;
break master;
}
}
break;
case "snacks":
for (var i = 0; i < snacks.length; i++) {
if (snacks[i].name == chipName) {
outField.value = snacks[i].price;
break master;
}
}
break;
default:
outField.value = "Not Found";
break;
}
Instead of AddEvent, you can use addEventListener. For example:
var chips = document.getElementById('chips');
chips.addEventListener('change', getPrice);
here two level selection are given with select tag , i want to make one more level by adding one more select tag.
if i selected madhya pradesh from first select tag then selected Rewa from second selection tag then option list should come into third selection tag with reference to Rewa such as Rewa appeared with respect to madhya pradesh.
tahshil[Rewa] =
{"Huzur","Hanumana","Teonthar","Mangawan","Jawa","Sirmour",
"Mauganj","Naigarhi","Semaria","Gurh","Raipur - Karchuliyan"}
<html>
<head>
<script type="text/javascript">
var countries = [ ];
countries["Madhya Pradesh"] = ["Indore","Jabalpur","Bhopal","Raisen","Rajgarh","Sehore","Vidisha","Morena","Sheopur","Bhind","Ashoknagar","Shivpuri","Rewa"];
countries["Uttar Pradesh"] = ["Allahabad","Moradabad","Ghaziabad","Azamgarh", "Lucknow","Kanpur Nagar","Jaunpur","Sitapur","Bareilly","Gorakhpur","Agra"];
function switchCountry(selCountry)
{
var citySel = selCountry.form.City;
for ( var s = citySel.options.length-1; s > 0; --s )
{
citySel.options[s] = null;
}
var chosen = selCountry.options[selCountry.selectedIndex].text;
var cList = countries[chosen];
if ( cList != null )
{
for ( var i = 0; i < cList.length; ++i )
{
citySel.options[i+1] = new Option(cList[i],cList[i]);
}
}
}
</script>
</head>
<body>
<br>
<form>
<center>
<h3>Select State of shop : <select name="Country" onchange="switchCountry(this);">
<option value = "">Choose state</option>
<option value="mdp">Madhya Pradesh</option>
<option value="utp">Uttar Pradesh</option>
</select></h3>
<h3>Select District place : <select name="City">
<option>Choose City</option>
</select>
<h3>Select Tehsil place : <select name="Tehsil">
<option>Choose City</option>
</select>
</h3><br>
</center>
</form><br><br><br>
</body>
</html>
how to make third level selection ?
i made a solution for my question as follow:
<script type="text/javascript">
var countries = [ ];
countries["Madhya Pradesh"] = ["Indore","Jabalpur","Bhopal","Raisen","Rajgarh","Sehore","Vidisha","Morena","Sheopur","Bhind","Ashoknagar","Shivpuri","Rewa"];
countries["Uttar Pradesh"] = ["Allahabad","Moradabad","Ghaziabad","Azamgarh", "Lucknow","Kanpur Nagar","Jaunpur","Sitapur","Bareilly","Gorakhpur","Agra"];
var Tehsil = [ ];
Tehsil["Rewa"] = ["Huzur","Hanumana","Teonthar","Mangawan","Jawa","Sirmour", "Mauganj","Naigarhi","Semaria","Gurh","Raipur - Karchuliyan"];
function switchCountry(selCountry)
{
var citySel = selCountry.form.City;
for ( var s = citySel.options.length-1; s > 0; --s )
{
citySel.options[s] = null;
}
var chosen = selCountry.options[selCountry.selectedIndex].text;
var cList = countries[chosen];
if ( cList != null )
{
for ( var i = 0; i < cList.length; ++i )
{
citySel.options[i+1] = new Option(cList[i],cList[i]);
}
}
}
function switchCountry1(selCountry)
{
var citySel = selCountry.form.Tehsil;
for ( var s = citySel.options.length-1; s > 0; --s )
{
citySel.options[s] = null;
}
var chosen = selCountry.options[selCountry.selectedIndex].text;
var cList = Tehsil[chosen];
if ( cList != null )
{
for ( var i = 0; i < cList.length; ++i )
{
citySel.options[i+1] = new Option(cList[i],cList[i]);
}
}
}
</script>
</head>
<body>
<br>
<form>
<center>
<h3>Select State of shop : <select name="Country" onchange="switchCountry(this);">
<option value = "">Choose state</option>
<option value="mdp">Madhya Pradesh</option>
<option value="utp">Uttar Pradesh</option>
</select></h3>
<h3>Select District place : <select name="City" onchange="switchCountry1(this);">
<option>Choose City</option>
</select>
<h3>Select Tehsil place : <select name="Tehsil">
<option>Choose Tehsil</option>
</select>
</h3><br>
</center>
</form><br><br><br>
</body>
</html>
I want to be able to jump to the web page when the option is selected from the third drop down menu.
Javascript:
var stateObject = {
"California": {
"Monterey": ["Salinas", "Gonzales"],
"Alameda": ["Oakland", "Berkeley"]
},
"Oregon": {
"Douglas": ["Roseburg", "Winston"],
"Jackson": ["Medford", "Jacksonville"]
}
}
window.onload = function () {
var stateSel = document.getElementById("stateSel"),
countySel = document.getElementById("countySel"),
citySel = document.getElementById("citySel");
for (var state in stateObject) {
stateSel.options[stateSel.options.length] = new Option(state, state);
}
stateSel.onchange = function () {
countySel.length = 1; // remove all options bar first
citySel.length = 1; // remove all options bar first
if (this.selectedIndex < 1) return; // done
for (var county in stateObject[this.value]) {
countySel.options[countySel.options.length] = new Option(county, county);
}
}
stateSel.onchange(); // reset in case page is reloaded
countySel.onchange = function () {
citySel.length = 1; // remove all options bar first
if (this.selectedIndex < 1) return; // done
var cities = stateObject[stateSel.value][this.value];
for (var i = 0; i < cities.length; i++) {
citySel.options[citySel.options.length] = new Option(cities[i], cities[i]);
}
}
}
HTML:
<form name="myform" id="myForm">
<select name="optone" id="stateSel" size="1">
<option value="" selected="selected">Select state</option>
</select>
<br>
<br>
<select name="opttwo" id="countySel" size="1">
<option value="" selected="selected">Please select state first</option>
</select>
<br>
<br>
<select name="optthree" id="citySel" size="1">
<option value="" selected="selected">Please select county first</option>
</select>
</form>
example
Any idea how to resolve this?
Adding:
citySel.onchange = function(){
window.location.href = "http://google.it";
}
At the bottom of window.onload = function () { should do the job.
You probabily want to do something like:
citySel.onchange = function(){
switch(citySel.value){
case "Salinas":
window.location.href = "http://salinas.com";
break;
case "Gonzales":
if(stateSel.value == "Something"){
window.location.href = "http://gonzales.com";
}else if(stateSel.value == "Else"){
window.location.href = "http://gonzales.com";
}
break;
}
Add onchange handler to your city select.
var stateObject = {
"California": {
"Monterey": ["Salinas", "Gonzales"],
"Alameda": ["Oakland", "Berkeley"]
},
"Oregon": {
"Douglas": ["Roseburg", "Winston"],
"Jackson": ["Medford", "Jacksonville"]
}
}
window.onload = function () {
var stateSel = document.getElementById("stateSel"),
countySel = document.getElementById("countySel"),
citySel = document.getElementById("citySel");
for (var state in stateObject) {
stateSel.options[stateSel.options.length] = new Option(state, state);
}
stateSel.onchange = function () {
countySel.length = 1; // remove all options bar first
citySel.length = 1; // remove all options bar first
if (this.selectedIndex < 1) return; // done
for (var county in stateObject[this.value]) {
countySel.options[countySel.options.length] = new Option(county, county);
}
}
stateSel.onchange(); // reset in case page is reloaded
countySel.onchange = function () {
citySel.length = 1; // remove all options bar first
if (this.selectedIndex < 1) return; // done
var cities = stateObject[stateSel.value][this.value];
for (var i = 0; i < cities.length; i++) {
citySel.options[citySel.options.length] = new Option(cities[i], cities[i]);
}
}
citySel.onchange = function () {
if(stateSel.options.length > 0 && countySel.options.length) {
alert('County: '+countySel.value + ' - State: ' +stateSel.value + ' - City: ' +citySel.value);
location.href = '/'; // your link
}
}
}
<form name="myform" id="myForm">
<select name="optone" id="stateSel" size="1">
<option value="" selected="selected">Select state</option>
</select>
<br>
<br>
<select name="opttwo" id="countySel" size="1">
<option value="" selected="selected">Please select state first</option>
</select>
<br>
<br>
<select name="optthree" id="citySel" size="1">
<option value="" selected="selected">Please select county first</option>
</select>
</form>
The following line can be used in an onChange event for the select box:
window.location.replace("http://YOUR-URL-HERE.com");
var stateObject = {
"California": {
"Monterey": ["Salinas", "Gonzales"],
"Alameda": ["Oakland", "Berkeley"]
},
"Oregon": {
"Douglas": ["Roseburg", "Winston"],
"Jackson": ["Medford", "Jacksonville"]
}
}
window.onload = function () {
var stateSel = document.getElementById("stateSel"),
countySel = document.getElementById("countySel"),
citySel = document.getElementById("citySel");
for (var state in stateObject) {
stateSel.options[stateSel.options.length] = new Option(state, state);
}
stateSel.onchange = function () {
countySel.length = 1; // remove all options bar first
citySel.length = 1; // remove all options bar first
if (this.selectedIndex < 1) return; // done
for (var county in stateObject[this.value]) {
countySel.options[countySel.options.length] = new Option(county, county);
}
}
stateSel.onchange(); // reset in case page is reloaded
countySel.onchange = function () {
citySel.length = 1; // remove all options bar first
if (this.selectedIndex < 1) return; // done
var cities = stateObject[stateSel.value][this.value];
for (var i = 0; i < cities.length; i++) {
citySel.options[citySel.options.length] = new Option(cities[i], cities[i]);
}
}
citySel.onchange = function () {
//redirect page
window.location.replace("http://stackoverflow.com");
}
}
<form name="myform" id="myForm">
<select name="optone" id="stateSel" size="1">
<option value="" selected="selected">Select state</option>
</select>
<br>
<br>
<select name="opttwo" id="countySel" size="1">
<option value="" selected="selected">Please select state first</option>
</select>
<br>
<br>
<select name="optthree" id="citySel" size="1">
<option value="" selected="selected">Please select county first</option>
</select>
</form>
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'