Jump to content

[SOLVED] Java Dropdown Population Code Change


mikemessiah

Recommended Posts

Hi guys,

 

This code works perfectly, the only thing is that when you submit the form it sends the number (ie. arrItemsGrp1[6] = 2;)

instead of the selection or word (ie. arrItems1[6] = "Boat";)

 

Please tell me there is a way to send the selection/Word... I really hope there is. I imagine there must be a way by adding an if statement as the submit button is pushed it sends the corresponding name instead of the number.

 

Pleeeaasee help  ???

 

Byron

 

Here is the code...

 

<!-- TWO STEPS TO INSTALL DROPDOWN BOX POPULATION:

 

  1.  Copy the coding into the HEAD of your HTML document

  2.  Add the last code into the BODY of your HTML document  -->

 

<!-- STEP ONE: Paste this code into the HEAD of your HTML document  -->

 

<HEAD>

 

<script type="text/javascript">

<!--

/* This script and many more are available free online at

The JavaScript Source!! http://javascript.internet.com

Revised by: DeWayne Whitaker :: http://www.aecdfw.com

Original by: Andrew Berry */

 

var arrItems1 = new Array();

var arrItemsGrp1 = new Array();

 

arrItems1[3] = "Truck";

arrItemsGrp1[3] = 1;

arrItems1[4] = "Train";

arrItemsGrp1[4] = 1;

arrItems1[5] = "Car";

arrItemsGrp1[5] = 1;

 

arrItems1[6] = "Boat";

arrItemsGrp1[6] = 2;

arrItems1[7] = "Submarine";

arrItemsGrp1[7] = 2;

 

arrItems1[0] = "Planes";

arrItemsGrp1[0] = 3;

arrItems1[1] = "Ultralight";

arrItemsGrp1[1] = 3;

arrItems1[2] = "Glider";

arrItemsGrp1[2] = 3;

 

var arrItems2 = new Array();

var arrItemsGrp2 = new Array();

 

arrItems2[21] = "747";

arrItemsGrp2[21] = 0

arrItems2[22] = "Cessna";

arrItemsGrp2[22] = 0

 

arrItems2[31] = "Kolb Flyer";

arrItemsGrp2[31] = 1

arrItems2[34] = "Kitfox";

arrItemsGrp2[34] = 1

 

arrItems2[35] = "Schwietzer Glider";

arrItemsGrp2[35] = 2

 

arrItems2[99] = "Chevy Malibu";

arrItemsGrp2[99] = 5

arrItems2[100] = "Lincoln LS";

arrItemsGrp2[100] = 5

arrItems2[57] = "BMW Z3";

arrItemsGrp2[57] = 5

 

arrItems2[101] = "F-150";

arrItemsGrp2[101] = 3

arrItems2[102] = "Tahoe";

arrItemsGrp2[102] = 3

 

arrItems2[103] = "Freight Train";

arrItemsGrp2[103] = 4

arrItems2[104] = "Passenger Train";

arrItemsGrp2[104] = 4

 

arrItems2[105] = "Oil Tanker";

arrItemsGrp2[105] = 6

arrItems2[106] = "Fishing Boat";

arrItemsGrp2[106] = 6

 

arrItems2[200] = "Los Angelas Class";

arrItemsGrp2[200] = 7

arrItems2[201] = "Kilo Class";

arrItemsGrp2[201] = 7

arrItems2[203] = "Seawolf Class";

arrItemsGrp2[203] = 7

 

function selectChange(control, controlToPopulate, ItemArray, GroupArray) {

  var myEle ;

  var x ;

  // Empty the second drop down box of any choices

  for (var q=controlToPopulate.options.length;q>=0;q--) controlToPopulate.options[q]=null;

  if (control.name == "firstChoice") {

    // Empty the third drop down box of any choices

    for (var q=form.thirdChoice.options.length;q>=0;q--) form.thirdChoice.options[q] = null;

}

  // ADD Default Choice - in case there are no values

  myEle = document.createElement("option") ;

  myEle.value = 0 ;

  myEle.text = "[sELECT]" ;

  // controlToPopulate.add(myEle) ;

  controlToPopulate.appendChild(myEle)

  // Now loop through the array of individual items

  // Any containing the same child id are added to

  // the second dropdown box

  for ( x = 0 ; x < ItemArray.length  ; x++ ) {

    if ( GroupArray[x] == control.value ) {

      myEle = document.createElement("option") ;

      //myEle.value = x ;

      myEle.setAttribute('value',x);

      // myEle.text = ItemArray[x] ;

      var txt = document.createTextNode(ItemArray[x]);

      myEle.appendChild(txt)

      // controlToPopulate.add(myEle) ;

      controlToPopulate.appendChild(myEle)

    }

  }

}

 

function selectChange(control, controlToPopulate, ItemArray, GroupArray) {

  var myEle ;

  var x ;

  // Empty the second drop down box of any choices

  for (var q=controlToPopulate.options.length;q>=0;q--) controlToPopulate.options[q]=null;

  if (control.name == "firstChoice") {

    // Empty the third drop down box of any choices

    for (var q=form.thirdChoice.options.length;q>=0;q--) form.thirdChoice.options[q] = null;

  }

  // ADD Default Choice - in case there are no values

  myEle=document.createElement("option");

  theText=document.createTextNode("[sELECT]");

  myEle.appendChild(theText);

  myEle.setAttribute("value","0");

  controlToPopulate.appendChild(myEle);

  // Now loop through the array of individual items

  // Any containing the same child id are added to

  // the second dropdown box

  for ( x = 0 ; x < ItemArray.length  ; x++ ) {

    if ( GroupArray[x] == control.value ) {

      myEle = document.createElement("option") ;

      //myEle.value = x ;

      myEle.setAttribute("value",x);

      // myEle.text = ItemArray[x] ;

      var txt = document.createTextNode(ItemArray[x]);

      myEle.appendChild(txt)

      // controlToPopulate.add(myEle) ;

      controlToPopulate.appendChild(myEle)

    }

  }

}

// -->

</script>

</HEAD>

 

<!-- STEP TWO: Copy this code into the BODY of your HTML document  -->

 

<BODY>

 

<form name=form>

<table align="center">

  <tr>

    <td>

      <select id="firstChoice" name="firstChoice" onchange="selectChange(this, form.secondChoice, arrItems1, arrItemsGrp1);">

        <option value="0" selected>[sELECT]</option>

        <option value="1">Land</option>

        <option value="2">Sea</option>

        <option value="3">Air</option>

      </select>

    </td><td>

      <select id="secondChoice" name="secondChoice" onchange="selectChange(this, form.thirdChoice, arrItems2, arrItemsGrp2);">

      </select>

      <select id="thirdChoice" name="thirdChoice">

      </select>

    </td>

  </tr>

</table>

</form>

 

<p><center>

<font face="arial, helvetica" size"-2">Free JavaScripts provided<br>

by <a href="http://javascriptsource.com">The JavaScript Source</a></font>

</center><p>

 

<!-- Script Size:  5.38 KB -->

Link to comment
Share on other sites

Here is some code I have that does the same thing, but is a bit more manageable (plus it uses the text as the value). You just need to change it for your values.

 

<html>
<head>

<script type="text/javascript">


// State lists
var states = new Array();

states['Canada'] = new Array('Alberta','British Columbia','Ontario');
states['Mexico'] = new Array('Baja California','Chihuahua','Jalisco');
states['United States'] = new Array('California','Florida','New York');


// City lists
var cities = new Array();

cities['Canada'] = new Array();
cities['Canada']['Alberta']          = new Array('Edmonton','Calgary');
cities['Canada']['British Columbia'] = new Array('Victoria','Vancouver');
cities['Canada']['Ontario']          = new Array('Toronto','Hamilton');

cities['Mexico'] = new Array();
cities['Mexico']['Baja California'] = new Array('Tijauna','Mexicali');
cities['Mexico']['Chihuahua']       = new Array('Ciudad Juárez','Chihuahua');
cities['Mexico']['Jalisco']         = new Array('Guadalajara','Chapala');

cities['United States'] = new Array();
cities['United States']['California'] = new Array('Los Angeles','San Francisco');
cities['United States']['Florida']    = new Array('Miami','Orlando');
cities['United States']['New York']   = new Array('Buffalo','New York');


function setStates(){

  cntrySel = document.getElementById('country');
  stateSel = document.getElementById('state');

  stateList = states[cntrySel.value];

  changeSelect(stateSel, stateList);
  setCities();

}

function setCities(){

  cntrySel = document.getElementById('country');
  stateSel = document.getElementById('state');
  citySel  = document.getElementById('city');

  cityList = cities[cntrySel.value][stateSel.value];

  changeSelect(citySel, cityList);

}
//**************************************************************************//
// FUNCTION changeSelect(fieldObj, valuesAry, [optTextAry], [selectedVal])
//
//**************************************************************************//
function changeSelect(fieldObj, valuesAry, optTextAry, selectedValue) {

  //Clear the select list
  fieldObj.options.length = 0;

  //Set the option text to the values if not passed
  optTextAry = (optTextAry)?optTextAry:valuesAry;

  //Itterate through the list and create the options
  for (i in valuesAry) {
    selectFlag = (selectedValue && selectedValue==valuesAry[i])?true:false;
    fieldObj.options[fieldObj.length] = new Option(optTextAry[i], valuesAry[i], false, selectFlag);
  }

}

</script>

</head>

<body onload="setStates();">
<form name="test" method="POST" action="processingpage.php">

Country: 
<select name="country" id="country" onchange="setStates();">
  <option value="Canada">Canada</option>
  <option value="Mexico">Mexico</option>
  <option value="United States">United States</option>
</select>
<br>

State: 
<select name="state" id="state" onchange="setCities();">
  <option value="">Please select a Country</option>
</select>
<br>

City: 
<select name="city"  id="city">
  <option value="">Please select a Country</option>
</select>
</form>
</body>
</html>

Link to comment
Share on other sites

No it's definitely not the only way. I just didn't want to spend the time to learnt he code you posted to try and fix it when I already had a solution available.

 

But, I think that the format which my code uses is much easier to maintain, IMO.

Link to comment
Share on other sites

Is there any way to put brackets in the code without it messing it up? I have put deliminators /(    /)  to all brackets but is still seems to not want to work?

 

any ideas?

 

<html>
<head>

<script type="text/javascript">

// Province lists
var province = new Array();

province['Italy'] = new Array();

province['Namibia'] = new Array( 'Any','Academia / Pioneers Park / Hochland','Auasblick / Olympia','Bethanie','Caprivi Region','Gobabis','Henties Bay','Karibib','Keetmanshoop','lein Windhoek / Eros / Avis / Ludwigsdorf','Kleine Kuppe / Cimbabasia / Prosperitas / Rocky Crest','Langstrand / Dolfynstrand','Luderitz','Luxury hill / Suiderhof / Windhoek West','Maltahohe','Hardap Region','Monte Christo','Okahandja / Okahandja District','Omaruru','Ondangwa','Oshakati','Otjiwarongo','Otjiwarongo District','Rundu','Swakopmund','Tsumeb','Walvis Bay','Windhoek Central','Windhoek District');

province['South Africa'] = new Array('Northern Cape','Western Cape','Eastern Cape','Free State','North West','Gauteng','KZN','Mpumalanga','Limpopo');

// City lists
var cities = new Array();

cities['Namibia'] = new Array();

cities['Namibia']['Any'] = new Array('Any');

cities['South Africa'] = new Array();

cities['South Africa']['Northern Cape']		 = new Array( 'Any','Tswala','Kuruman','Augrabies Falls','Upington','Kakamas','Pofadder','Kimberly','Alexander Bay','Okiep','Springbok','Niewoudtville','Garies','Calvinia','Hopetown','De Aar','Colesburg','Hanover');

cities['South Africa']['Western Cape']       = new Array('Cape Flats','Cape Town City Bowl and Atlantic Seaboard','Cape Town Northern Suburbs','Garden Route','Great Karoo','Milnerton','Tableview and Blaauwberg','Overberg','Peninsula \(Simons Town to Hout Bay\)','Somerset West and Boland','Southern Suburbs \(Tokai to Pinelands\)','West Coast');

cities['South Africa']['Eastern Cape']       = new Array('East Cape Interior','East London, Eastern Karoo','EC Jeffreys Bay to Tsitsikamma','EC Wild Coast','Grahamstown and Surrounds','Port Alfred and Coastal Towns','Port Elizabeth');

cities['South Africa']['Free State']         = new Array('Bethlehem / Harrismith / Clarence & Region','Bloemfontein & Central Freestate','Ficksburg / Clocolan / Rosendal & Region','Vaalriver / Parys & Region','Vaaltriangle / Vaalpark / Sasolburg','Welkom / Goudveld & Region',);

cities['South Africa']['North West']         = new Array('Carltonville','Derby','Fochville','Groot Marico','Hartbeesfontein','Klerksdorp','Koster','Lichtenburg','Mafikeng','Makwassie','Northam','Orkney','Potchefstroom','Rustenburg','Sannieshof','Schweizer Reyneke','Stilfontein','Swartruggens','Ventersdorp','Vredefort','Vryburg','Wolmaranstad','Zeerust');

cities['South Africa']['Gauteng']       	 = new Array('Alberton Southern suburbs','Benoni','Boksburg','Brakpan','Centurion','Edenvale','Germiston','Johannesburg CBD and Bruma','Kempton Park','Midrand','Nigel & Heidelberg','Northcliff and Melville \(West\)','Northern Pretoria','Pretoria Central and Old East','Pretoria East','Randburg and Ferndale \(North West\)','Roodepoort \(Far West\) and Krugersdorp','Rosebank and Parktown \(Central\)','Sandton and Bryanston \(North\)','Soweto','Springs','Sunninghill','Lonehill and Fourways','Vereeniging','Vanderbijlpark and Vaal Dam','Wynburg \(East\)');

cities['South Africa']['KZN']       		 = new Array('Dolphin Coast','Durban Central North and CBD','Durban Central South','Durban North','Durban South','Durban Upper Highway','Durban West / Highway','KZN Midlands','KZN North Coast','KZN South Coast','Richards Bay');

cities['South Africa']['Mpumalanga']       	 = new Array('Barberton', 'Belfast', 'Bethal', 'Burgersfort', 'Carolina / Badplaas', 'Delmas', 'Dullstroom,' 'Ermelo / Chrissiesmeer', 'Graskop', 'Groblersdal', 'Hazyview', 'Hendrina', 'Kinross', 'Komatipoort', 'Lydenburg', 'Machadodorp', 'Malelane / Hectorspruit', 'Marloth Park', 'Middelburg', 'Nelspruit', 'Ohrigstad', 'PietRetief / Volksrust / Wakkerstroom', 'Rietkruil', 'Sabie', 'Secunda', 'Standerton', 'Sundra', 'Trichardt', 'Waterval Boven / Onder', 'White River', 'Witbank');

cities['South Africa']['Limpopo']        	 = new Array('Bela-Bela \(Warmbaths\) / Rooiberg, Hoedspruit','Makhado \(Louis Trichardt\) / Musina, Modimole \(Nylstroom\)','Mokopane \(Potgietersrus\), Mookgophong \(Naboomspruit\)','Phalaborwa','Polokwane \(Pietersburg\)','Thabazimbi / Lephalale \(Ellisras\)','Tzaneen / Duiwelskloof / Gravelotte','Vaalwater','Welgelegen');

// Towns lists
var towns = new Array();

towns['KZN'] = new Array();

towns['KZN']['Dolphin Coast']		 			= new Array('Ballito','Blythedale / Princes Grant','Chakas Rock / Salt Rock','La Mercy','Sheffield Beach','Stanger','Tongaat / Verulam','Umdloti','Westbrook','Zinkwazi Beach');

towns['KZN']['Durban Central North and CBD']	= new Array('Beachfront','Berea','CBD','Morningside','Overport / Puntan\'s Hill','Point Waterfront','Sherwood / Sydenham / West Riding / Asherville');

towns['KZN']['Durban Central South']		 	= new Array('000000');

towns['KZN']['Durban North']		 			= new Array('000000');

towns['KZN']['Durban South']		 			= new Array('000000');

towns['KZN']['Durban Upper Highway']		 	= new Array('000000');

towns['KZN']['Durban West / Highway']		 	= new Array('000000');

towns['KZN']['KZN Midlands']		 			= new Array('000000');

towns['KZN']['KZN North Coast']		 			= new Array('000000');

towns['KZN']['KZN South Coast']		 			= new Array('000000');

towns['KZN']['Richards Bay']		 			= new Array('000000');


function setProvince(){

  cntrySel = document.getElementById('country');
  stateSel = document.getElementById('province');

  stateList = province[cntrySel.value];

  changeSelect(stateSel, stateList);
  setCities();

}

function setCities(){

  cntrySel = document.getElementById('country');
  provinceSel = document.getElementById('province');
  citySel  = document.getElementById('city');

  cityList = cities[cntrySel.value][stateSel.value];

  changeSelect(citySel, cityList);

}

function setTowns(){

  cntrySel = document.getElementById('country');
  provinceSel = document.getElementById('province');
  citySel  = document.getElementById('city');
  townSel  = document.getElementById('town');  
  
  townList = towns[cntrySel.value][stateSel.value][citySel.value];

  changeSelect(townSel, townList);

}


//**************************************************************************//
// FUNCTION changeSelect(fieldObj, valuesAry, [optTextAry], [selectedVal])
//
//**************************************************************************//
function changeSelect(fieldObj, valuesAry, optTextAry, selectedValue) {

  //Clear the select list
  fieldObj.options.length = 0;

  //Set the option text to the values if not passed
  optTextAry = (optTextAry)?optTextAry:valuesAry;

  //Itterate through the list and create the options
  for (i in valuesAry) {
    selectFlag = (selectedValue && selectedValue==valuesAry[i])?true:false;
    fieldObj.options[fieldObj.length] = new Option(optTextAry[i], valuesAry[i], false, selectFlag);
  }

}

</script>

</head>

<body onLoad="setProvince();">
<form name="test" method="POST" action="processingpage.php">

<label>Country:</label> 
<select name="country" id="country" onChange="setProvince();">
  <option value="Italy">Italy</option>
  <option value="Namibia">Namibia</option>
  <option value="South Africa" selected>South Africa</option>
</select>
<br>

<label>Province:</label>
<select name="province" id="province" onChange="setCities();">
  <option value="" selected>-- Any --</option>
</select>
<br>

<label>City:</label>
<select name="city"  id="city" onChange="setTowns();">
  <option value="" selected>-- Any --</option>
</select>
<br>

<label>Town:</label>
<select name="town"  id="town" >
  <option value="" selected>-- Any --</option>
</select>

</form>
</body>
</html>

Link to comment
Share on other sites

You don't need to escape the parentheses at all the problem was that you had a couple of misplaced commas in your array declarations. Here is the corrected code

 

// Province lists
var province = new Array();

province['Italy'] = new Array();

province['Namibia'] = new Array( 'Any','Academia / Pioneers Park / Hochland','Auasblick / Olympia','Bethanie','Caprivi Region','Gobabis','Henties Bay','Karibib','Keetmanshoop','lein Windhoek / Eros / Avis / Ludwigsdorf','Kleine Kuppe / Cimbabasia / Prosperitas / Rocky Crest','Langstrand / Dolfynstrand','Luderitz','Luxury hill / Suiderhof / Windhoek West','Maltahohe','Hardap Region','Monte Christo','Okahandja / Okahandja District','Omaruru','Ondangwa','Oshakati','Otjiwarongo','Otjiwarongo District','Rundu','Swakopmund','Tsumeb','Walvis Bay','Windhoek Central','Windhoek District');

province['South Africa'] = new Array('Northern Cape','Western Cape','Eastern Cape','Free State','North West','Gauteng','KZN','Mpumalanga','Limpopo');

// City lists
var cities = new Array();

cities['Namibia'] = new Array();

cities['Namibia']['Any'] = new Array('Any');

cities['South Africa'] = new Array();

cities['South Africa']['Northern Cape']	= new Array(
        'Any','Tswala','Kuruman','Augrabies Falls','Upington','Kakamas','Pofadder','Kimberly','Alexander Bay',
        'Okiep','Springbok','Niewoudtville','Garies','Calvinia','Hopetown','De Aar','Colesburg','Hanover');

cities['South Africa']['Western Cape']  = new Array(
        'Cape Flats','Cape Town City Bowl and Atlantic Seaboard','Cape Town Northern Suburbs','Garden Route',
        'Great Karoo','Milnerton','Tableview and Blaauwberg','Overberg','Peninsula (Simons Town to Hout Bay)',
        'Somerset West and Boland','Southern Suburbs (Tokai to Pinelands)','West Coast');

cities['South Africa']['Eastern Cape']  = new Array(
        'East Cape Interior','East London, Eastern Karoo','EC Jeffreys Bay to Tsitsikamma','EC Wild Coast',
        'Grahamstown and Surrounds','Port Alfred and Coastal Towns','Port Elizabeth');

//cities['South Africa']['Free State']  = new Array(
        'Bethlehem / Harrismith / Clarence & Region','Bloemfontein & Central Freestate',
        'Ficksburg / Clocolan / Rosendal & Region','Vaalriver / Parys & Region',
        'Vaaltriangle / Vaalpark / Sasolburg','Welkom / Goudveld & Region');

cities['South Africa']['North West']    = new Array(
        'Carltonville','Derby','Fochville','Groot Marico','Hartbeesfontein','Klerksdorp','Koster','Lichtenburg',
        'Mafikeng','Makwassie','Northam','Orkney','Potchefstroom','Rustenburg','Sannieshof','Schweizer Reyneke',
        'Stilfontein','Swartruggens','Ventersdorp','Vredefort','Vryburg','Wolmaranstad','Zeerust');

cities['South Africa']['Gauteng']       = new Array(
        'Alberton Southern suburbs','Benoni','Boksburg','Brakpan','Centurion','Edenvale','Germiston',
        'Johannesburg CBD and Bruma','Kempton Park','Midrand','Nigel & Heidelberg','Northcliff and Melville (West)',
        'Northern Pretoria','Pretoria Central and Old East','Pretoria East','Randburg and Ferndale (North West)',
        'Roodepoort (Far West) and Krugersdorp','Rosebank and Parktown (Central)','Sandton and Bryanston (North)',
        'Soweto','Springs','Sunninghill','Lonehill and Fourways','Vereeniging','Vanderbijlpark and Vaal Dam','Wynburg (East)');

cities['South Africa']['KZN']           = new Array(
        'Dolphin Coast','Durban Central North and CBD','Durban Central South','Durban North','Durban South',
        'Durban Upper Highway','Durban West / Highway','KZN Midlands','KZN North Coast','KZN South Coast','Richards Bay');

cities['South Africa']['Mpumalanga']    = new Array(
        'Barberton', 'Belfast', 'Bethal', 'Burgersfort', 'Carolina / Badplaas', 'Delmas', 'Dullstroom',
        'Ermelo / Chrissiesmeer', 'Graskop', 'Groblersdal', 'Hazyview', 'Hendrina', 'Kinross', 'Komatipoort',
        'Lydenburg', 'Machadodorp', 'Malelane / Hectorspruit', 'Marloth Park', 'Middelburg', 'Nelspruit', 'Ohrigstad',
        'PietRetief / Volksrust / Wakkerstroom', 'Rietkruil', 'Sabie', 'Secunda', 'Standerton', 'Sundra', 'Trichardt',
        'Waterval Boven / Onder', 'White River', 'Witbank');

cities['South Africa']['Limpopo']       = new Array(
        'Bela-Bela (Warmbaths) / Rooiberg, Hoedspruit','Makhado (Louis Trichardt) / Musina, Modimole (Nylstroom)',
        'Mokopane (Potgietersrus), Mookgophong (Naboomspruit)','Phalaborwa','Polokwane (Pietersburg)',
        'Thabazimbi / Lephalale (Ellisras)','Tzaneen / Duiwelskloof / Gravelotte','Vaalwater','Welgelegen');

// Towns lists
var towns = new Array();

towns['KZN'] = new Array();

towns['KZN']['Dolphin Coast'] = new Array(
        'Ballito','Blythedale / Princes Grant','Chakas Rock / Salt Rock','La Mercy','Sheffield Beach','Stanger',
        'Tongaat / Verulam','Umdloti','Westbrook','Zinkwazi Beach');

towns['KZN']['Durban Central North and CBD'] = new Array(
        'Beachfront','Berea','CBD','Morningside','Overport / Puntan\'s Hill','Point Waterfront',
        'Sherwood / Sydenham / West Riding / Asherville');

towns['KZN']['Durban Central South'] = new Array('000000');

towns['KZN']['Durban North'] = new Array('000000');

towns['KZN']['Durban South'] = new Array('000000');

towns['KZN']['Durban Upper Highway'] = new Array('000000');

towns['KZN']['Durban West / Highway'] = new Array('000000');

towns['KZN']['KZN Midlands'] = new Array('000000');

towns['KZN']['KZN North Coast'] = new Array('000000');

towns['KZN']['KZN South Coast'] = new Array('000000');

towns['KZN']['Richards Bay'] = new Array('000000');

Link to comment
Share on other sites

My Towns dont seem to be populating?

 

I added function setTowns() is there anything else I need to do? I am really sorry for this. but once you show me I will remember!

 

Thanks so much.

 

function setProvince(){

  cntrySel = document.getElementById('country');
  stateSel = document.getElementById('province');

  stateList = province[cntrySel.value];

  changeSelect(stateSel, stateList);
  setCities();

}

function setCities(){

  cntrySel = document.getElementById('country');
  provinceSel = document.getElementById('province');
  citySel  = document.getElementById('city');

  cityList = cities[cntrySel.value][stateSel.value];

  changeSelect(citySel, cityList);

}

function setTowns(){

  cntrySel = document.getElementById('country');
  provinceSel = document.getElementById('province');
  citySel  = document.getElementById('city');
  townSel  = document.getElementById('town');  
  
  townList = towns[cntrySel.value][stateSel.value][citySel.value];

  changeSelect(townSel, townList);

}


//**************************************************************************//
// FUNCTION changeSelect(fieldObj, valuesAry, [optTextAry], [selectedVal])
//
//**************************************************************************//
function changeSelect(fieldObj, valuesAry, optTextAry, selectedValue) {

  //Clear the select list
  fieldObj.options.length = 0;

  //Set the option text to the values if not passed
  optTextAry = (optTextAry)?optTextAry:valuesAry;

  //Itterate through the list and create the options
  for (i in valuesAry) {
    selectFlag = (selectedValue && selectedValue==valuesAry[i])?true:false;
    fieldObj.options[fieldObj.length] = new Option(optTextAry[i], valuesAry[i], false, selectFlag);
  }

}

Link to comment
Share on other sites

Fourth select still not populating....

 

http://www.soukopproperty.co.za/incl...rm-new-bup.php

 

I changed the code again... Pleeeaaassee help...

 

<html>
<head>

<script type="text/javascript">

// Province lists
var province = new Array();

province['Italy'] = new Array();

province['Namibia'] = new Array( 'Any','Academia / Pioneers Park / Hochland','Auasblick / Olympia','Bethanie','Caprivi Region','Gobabis','Henties Bay','Karibib','Keetmanshoop','lein Windhoek / Eros / Avis / Ludwigsdorf','Kleine Kuppe / Cimbabasia / Prosperitas / Rocky Crest','Langstrand / Dolfynstrand','Luderitz','Luxury hill / Suiderhof / Windhoek West','Maltahohe','Hardap Region','Monte Christo','Okahandja / Okahandja District','Omaruru','Ondangwa','Oshakati','Otjiwarongo','Otjiwarongo District','Rundu','Swakopmund','Tsumeb','Walvis Bay','Windhoek Central','Windhoek District');

province['South Africa'] = new Array('Northern Cape','Western Cape','Eastern Cape','Free State','North West','Gauteng','KZN','Mpumalanga','Limpopo');

// City lists
var cities = new Array();

cities['Namibia'] = new Array();

cities['Namibia']['Any'] = new Array('Any');

cities['South Africa'] = new Array();

cities['South Africa']['Northern Cape']	= new Array(
        'Any','Tswala','Kuruman','Augrabies Falls','Upington','Kakamas','Pofadder','Kimberly','Alexander Bay',
        'Okiep','Springbok','Niewoudtville','Garies','Calvinia','Hopetown','De Aar','Colesburg','Hanover');

cities['South Africa']['Western Cape']  = new Array(
        'Cape Flats','Cape Town City Bowl and Atlantic Seaboard','Cape Town Northern Suburbs','Garden Route',
        'Great Karoo','Milnerton','Tableview and Blaauwberg','Overberg','Peninsula (Simons Town to Hout Bay)',
        'Somerset West and Boland','Southern Suburbs (Tokai to Pinelands)','West Coast');

cities['South Africa']['Eastern Cape']  = new Array(
        'East Cape Interior','East London, Eastern Karoo','EC Jeffreys Bay to Tsitsikamma','EC Wild Coast',
        'Grahamstown and Surrounds','Port Alfred and Coastal Towns','Port Elizabeth');

cities['South Africa']['Free State']  = new Array(
        'Bethlehem / Harrismith / Clarence & Region','Bloemfontein & Central Freestate',
        'Ficksburg / Clocolan / Rosendal & Region','Vaalriver / Parys & Region',
        'Vaaltriangle / Vaalpark / Sasolburg','Welkom / Goudveld & Region');

cities['South Africa']['North West']    = new Array(
        'Carltonville','Derby','Fochville','Groot Marico','Hartbeesfontein','Klerksdorp','Koster','Lichtenburg',
        'Mafikeng','Makwassie','Northam','Orkney','Potchefstroom','Rustenburg','Sannieshof','Schweizer Reyneke',
        'Stilfontein','Swartruggens','Ventersdorp','Vredefort','Vryburg','Wolmaranstad','Zeerust');

cities['South Africa']['Gauteng']       = new Array(
        'Alberton Southern suburbs','Benoni','Boksburg','Brakpan','Centurion','Edenvale','Germiston',
        'Johannesburg CBD and Bruma','Kempton Park','Midrand','Nigel & Heidelberg','Northcliff and Melville (West)',
        'Northern Pretoria','Pretoria Central and Old East','Pretoria East','Randburg and Ferndale (North West)',
        'Roodepoort (Far West) and Krugersdorp','Rosebank and Parktown (Central)','Sandton and Bryanston (North)',
        'Soweto','Springs','Sunninghill','Lonehill and Fourways','Vereeniging','Vanderbijlpark and Vaal Dam','Wynburg (East)');

cities['South Africa']['KZN']           = new Array(
        'Dolphin Coast','Durban Central North and CBD','Durban Central South','Durban North','Durban South',
        'Durban Upper Highway','Durban West / Highway','KZN Midlands','KZN North Coast','KZN South Coast','Richards Bay');

cities['South Africa']['Mpumalanga']    = new Array(
        'Barberton', 'Belfast', 'Bethal', 'Burgersfort', 'Carolina / Badplaas', 'Delmas', 'Dullstroom',
        'Ermelo / Chrissiesmeer', 'Graskop', 'Groblersdal', 'Hazyview', 'Hendrina', 'Kinross', 'Komatipoort',
        'Lydenburg', 'Machadodorp', 'Malelane / Hectorspruit', 'Marloth Park', 'Middelburg', 'Nelspruit', 'Ohrigstad',
        'PietRetief / Volksrust / Wakkerstroom', 'Rietkruil', 'Sabie', 'Secunda', 'Standerton', 'Sundra', 'Trichardt',
        'Waterval Boven / Onder', 'White River', 'Witbank');

cities['South Africa']['Limpopo']       = new Array(
        'Bela-Bela (Warmbaths) / Rooiberg, Hoedspruit','Makhado (Louis Trichardt) / Musina, Modimole (Nylstroom)',
        'Mokopane (Potgietersrus), Mookgophong (Naboomspruit)','Phalaborwa','Polokwane (Pietersburg)',
        'Thabazimbi / Lephalale (Ellisras)','Tzaneen / Duiwelskloof / Gravelotte','Vaalwater','Welgelegen');

// Towns lists
var towns = new Array();

towns['South Africa']['KZN'] = new Array();

towns['South Africa']['KZN']['Dolphin Coast']		 			= new Array('Ballito','Blythedale / Princes Grant','Chakas Rock / Salt Rock','La Mercy','Sheffield Beach','Stanger','Tongaat / Verulam','Umdloti','Westbrook','Zinkwazi Beach');

towns['South Africa']['KZN']['Durban Central North and CBD']	= new Array('Beachfront','Berea','CBD','Morningside','Overport / Puntans Hill','Point Waterfront','Sherwood / Sydenham / West Riding / Asherville');

towns['South Africa']['KZN']['Durban Central South']		 	= new Array('Beachfront','Berea','CBD','Morningside');

towns['South Africa']['KZN']['Durban North']		 			= new Array('Beachfront','Berea','CBD','Morningside');

towns['South Africa']['KZN']['Durban South']		 			= new Array('Beachfront','Berea','CBD','Morningside');

towns['South Africa']['KZN']['Durban Upper Highway']		 	= new Array('Beachfront','Berea','CBD','Morningside');

towns['South Africa']['KZN']['Durban West / Highway']		 	= new Array('Beachfront','Berea','CBD','Morningside');

towns['South Africa']['KZN']['KZN Midlands']		 			= new Array('Beachfront','Berea','CBD','Morningside');

towns['South Africa']['KZN']['KZN North Coast']		 			= new Array('Beachfront','Berea','CBD','Morningside');

towns['South Africa']['KZN']['KZN South Coast']		 			= new Array('Beachfront','Berea','CBD','Morningside');

towns['South Africa']['KZN']['Richards Bay']		 			= new Array('Beachfront','Berea','CBD','Morningside');


function setProvince(){

  cntrySel = document.getElementById('country');
  provinceSel = document.getElementById('province');

  provinceList = province[cntrySel.value];

  changeSelect(provinceSel, provinceList);
  setCities();

}

function setCities(){

  cntrySel = document.getElementById('country');
  provinceSel = document.getElementById('province');
  citySel  = document.getElementById('city');

  cityList = cities[cntrySel.value][provinceSel.value];

  changeSelect(citySel, cityList);
  
  setTowns();
}

function setTowns(){

  cntrySel = document.getElementById('country');
  provinceSel = document.getElementById('province');
  citySel  = document.getElementById('city');
  townSel  = document.getElementById('town');  
  
  townList = towns[cntrySel.value][provinceSel.value][citySel.value];

  changeSelect(townSel, townList);

}


//**************************************************************************//
// FUNCTION changeSelect(fieldObj, valuesAry, [optTextAry], [selectedVal])
//
//**************************************************************************//
function changeSelect(fieldObj, valuesAry, optTextAry, selectedValue) {

  //Clear the select list
  fieldObj.options.length = 0;

  //Set the option text to the values if not passed
  optTextAry = (optTextAry)?optTextAry:valuesAry;

  //Itterate through the list and create the options
  for (i in valuesAry) {
    selectFlag = (selectedValue && selectedValue==valuesAry[i])?true:false;
    fieldObj.options[fieldObj.length] = new Option(optTextAry[i], valuesAry[i], false, selectFlag);
  }

}

</script>

</head>

<body onLoad="setProvince();">
<form name="test" method="POST" action="processingpage.php">

<label>Country:</label> 
<select name="country" id="country" onChange="setProvince();">
  <option value="Italy">Italy</option>
  <option value="Namibia">Namibia</option>
  <option value="South Africa" selected>South Africa</option>
</select>
<br>

<label>Province:</label>
<select name="province" id="province" onChange="setCities();">
  <option value="" selected>-- Any --</option>
</select>
<br>

<label>City:</label>
<select name="city"  id="city" onChange="setTowns();">
  <option value="" selected>-- Any --</option>
</select>
<br>

<label>Town:</label>
<select name="town"  id="town" >
  <option value="" selected>-- Any --</option>
</select>

</form>
</body>
</html>

Link to comment
Share on other sites

Made some major changes for your situation. Should be working now. I would suggest pullin all the Javascript code for the select boxes into an external file to make editing easier later on

<html>
<head>

<script type="text/javascript">

function getProvinceList(country) {

  provinceList = ['-- Any --'];

  switch (country) {

    case 'Namibia':
      provinceList = [
          'Any','Academia / Pioneers Park / Hochland','Auasblick / Olympia','Bethanie','Caprivi Region','Gobabis','Henties Bay',
          'Karibib','Keetmanshoop','lein Windhoek / Eros / Avis / Ludwigsdorf','Kleine Kuppe / Cimbabasia / Prosperitas / Rocky Crest',
          'Langstrand / Dolfynstrand','Luderitz','Luxury hill / Suiderhof / Windhoek West','Maltahohe','Hardap Region','Monte Christo',
          'Okahandja / Okahandja District','Omaruru','Ondangwa','Oshakati','Otjiwarongo','Otjiwarongo District','Rundu','Swakopmund',
          'Tsumeb','Walvis Bay','Windhoek Central','Windhoek District'];
      break;

    case 'South Africa':
      provinceList = ['Northern Cape','Western Cape','Eastern Cape','Free State','North West','Gauteng','KZN','Mpumalanga','Limpopo'];
      break;
  }

  return provinceList;
}

function getCityList(country, province) {

  cityList = ['-- Any --'];

  switch (country) {

    case 'South Africa':
      switch (province) {

        case 'Northern Cape':
          cityList = [
              'Any','Tswala','Kuruman','Augrabies Falls','Upington','Kakamas','Pofadder','Kimberly','Alexander Bay',
              'Okiep','Springbok','Niewoudtville','Garies','Calvinia','Hopetown','De Aar','Colesburg','Hanover'];          
          break;
        case 'Western Cape':
          cityList = [
              'Cape Flats','Cape Town City Bowl and Atlantic Seaboard','Cape Town Northern Suburbs','Garden Route',
              'Great Karoo','Milnerton','Tableview and Blaauwberg','Overberg','Peninsula (Simons Town to Hout Bay)',
              'Somerset West and Boland','Southern Suburbs (Tokai to Pinelands)','West Coast'];
          break;
        case 'Eastern Cape':
          cityList = [
              'East Cape Interior','East London, Eastern Karoo','EC Jeffreys Bay to Tsitsikamma','EC Wild Coast',
              'Grahamstown and Surrounds','Port Alfred and Coastal Towns','Port Elizabeth'];
          break;
        case 'Free State':
          cityList = [
              'Bethlehem / Harrismith / Clarence & Region','Bloemfontein & Central Freestate',
              'Ficksburg / Clocolan / Rosendal & Region','Vaalriver / Parys & Region',
              'Vaaltriangle / Vaalpark / Sasolburg','Welkom / Goudveld & Region'];
          break;
        case 'North West':
          cityList = [
              'Carltonville','Derby','Fochville','Groot Marico','Hartbeesfontein','Klerksdorp','Koster','Lichtenburg',
              'Mafikeng','Makwassie','Northam','Orkney','Potchefstroom','Rustenburg','Sannieshof','Schweizer Reyneke',
              'Stilfontein','Swartruggens','Ventersdorp','Vredefort','Vryburg','Wolmaranstad','Zeerust'];
          break;
        case 'Gauteng':
          cityList = [
              'Alberton Southern suburbs','Benoni','Boksburg','Brakpan','Centurion','Edenvale','Germiston',
              'Johannesburg CBD and Bruma','Kempton Park','Midrand','Nigel & Heidelberg','Northcliff and Melville (West)',
              'Northern Pretoria','Pretoria Central and Old East','Pretoria East','Randburg and Ferndale (North West)',
              'Roodepoort (Far West) and Krugersdorp','Rosebank and Parktown (Central)','Sandton and Bryanston (North)',
              'Soweto','Springs','Sunninghill','Lonehill and Fourways','Vereeniging','Vanderbijlpark and Vaal Dam','Wynburg (East)'];
          break;
        case 'KZN':
          cityList = [
              'Dolphin Coast','Durban Central North and CBD','Durban Central South','Durban North','Durban South',
              'Durban Upper Highway','Durban West / Highway','KZN Midlands','KZN North Coast','KZN South Coast','Richards Bay'];
          break;
        case 'Mpumalanga':
          cityList = [
              'Barberton', 'Belfast', 'Bethal', 'Burgersfort', 'Carolina / Badplaas', 'Delmas', 'Dullstroom',
              'Ermelo / Chrissiesmeer', 'Graskop', 'Groblersdal', 'Hazyview', 'Hendrina', 'Kinross', 'Komatipoort',
              'Lydenburg', 'Machadodorp', 'Malelane / Hectorspruit', 'Marloth Park', 'Middelburg', 'Nelspruit', 'Ohrigstad',
              'PietRetief / Volksrust / Wakkerstroom', 'Rietkruil', 'Sabie', 'Secunda', 'Standerton', 'Sundra', 'Trichardt',
              'Waterval Boven / Onder', 'White River', 'Witbank'];
          break;
        case 'Limpopo':
          cityList = [
              'Bela-Bela (Warmbaths) / Rooiberg, Hoedspruit','Makhado (Louis Trichardt) / Musina, Modimole (Nylstroom)',
              'Mokopane (Potgietersrus), Mookgophong (Naboomspruit)','Phalaborwa','Polokwane (Pietersburg)',
              'Thabazimbi / Lephalale (Ellisras)','Tzaneen / Duiwelskloof / Gravelotte','Vaalwater','Welgelegen'];
          break;
        case 'Mpumalanga':
          cityList = [];
          break;
      }
      break;
  }

  return cityList;
}


function getTownList(country, province, city) {

  townList = ['-- Any --'];

  switch (country) {

    case 'South Africa':
      switch (province) {

        case 'KZN':
          switch (city) {

            case 'Durban Central South':
              townList = ['Town1','Town2','Town3'];              
              break;
            case 'Durban North':
              townList = ['Town1','Town2','Town3'];              
              break;
            case 'Durban South':
              townList = ['Town1','Town2','Town3'];              
              break;
            case 'Durban Upper Highway':
              townList = ['Town1','Town2','Town3'];              
              break;
            case 'Durban West / Highway':
              townList = ['Town1','Town2','Town3'];              
              break;
            case 'KZN Midlands':
              townList = ['Town1','Town2','Town3'];              
              break;
            case 'KZN North Coast':
              townList = ['Town1','Town2','Town3'];              
              break;
            case 'KZN South Coast':
              townList = ['Town1','Town2','Town3'];              
              break;
            case 'Richards Bay':
              townList = ['Town1','Town2','Town3'];              
              break;
          }
          break;
      }
      break;
  }

  return townList;
}



function setProvince(){

  cntrySel = document.getElementById('country');
  prvncSel = document.getElementById('province');

  prvncList = getProvinceList(cntrySel.value);

  changeSelect(prvncSel, prvncList);
  setCities();

}

function setCities(){

  cntrySel = document.getElementById('country');
  prvncSel = document.getElementById('province');
  citySel  = document.getElementById('city');

  cityList = getCityList(cntrySel.value, prvncSel.value);

  changeSelect(citySel, cityList);

}

function setTowns(){

  cntrySel = document.getElementById('country');
  prvncSel = document.getElementById('province');
  citySel  = document.getElementById('city');
  townSel  = document.getElementById('town');  
  
  townList = getTownList(cntrySel.value, prvncSel.value, citySel.value);

  changeSelect(townSel, townList);

}


//**************************************************************************//
// FUNCTION changeSelect(fieldObj, valuesAry, [optTextAry], [selectedVal])
//
//**************************************************************************//
function changeSelect(fieldObj, valuesAry, optTextAry, selectedValue) {

  //Clear the select list
  fieldObj.options.length = 0;

  //Set the option text to the values if not passed
  optTextAry = (optTextAry)?optTextAry:valuesAry;

  //Itterate through the list and create the options
  for (i in valuesAry) {
    selectFlag = (selectedValue && selectedValue==valuesAry[i])?true:false;
    fieldObj.options[fieldObj.length] = new Option(optTextAry[i], valuesAry[i], false, selectFlag);
  }

}

</script>

</head>

<body onLoad="setProvince();">
<form name="test" method="POST" action="processingpage.php">

<label>Country:</label> 
<select name="country" id="country" onChange="setProvince();">
  <option value="Italy">Italy</option>
  <option value="Namibia">Namibia</option>
  <option value="South Africa" selected>South Africa</option>
</select>
<br>

<label>Province:</label>
<select name="province" id="province" onChange="setCities();">
  <option value="" selected>-- Any --</option>
</select>
<br>

<label>City:</label>
<select name="city"  id="city" onChange="setTowns();">
  <option value="" selected>-- Any --</option>
</select>
<br>

<label>Town:</label>
<select name="town"  id="town" >
  <option value="" selected>-- Any --</option>
</select>

</form>
</body>
</html>



Link to comment
Share on other sites

  • 3 months later...

Hi,

 

You helped me a few months back with drop down population.

 

I am looking to do the exact same thing only this time I only need the "Town" to populate. So the "Cities" will be hard coded and when selected it will populate the towns.

 

Pleaes could you help me out?

 

the site it is for is http://www.propafrica.co.za

 

Thanks in Advance.

 

Byron

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.