Jump to content


Photo

dynamic drop down lists


  • Please log in to reply
6 replies to this topic

#1 digitalgod

digitalgod
  • Members
  • PipPipPip
  • Advanced Member
  • 374 posts

Posted 25 April 2006 - 07:11 AM

Hey guys,

What I'm trying to do is have a user select his country and when that happens he state/province drop down automaticly populates according to the chosen country. I have that part working but I also want a 3rd drop down named City which populates with cities from the chosen state...

here's what I got, it works perfectly for Country and States but the Cities drop down always stays empty....

var postState = '<?= $_POST["state"] ?>';
var postCountry = '<?= $_POST["country"] ?>';
var postCity = '<?= $_POST["city"] ?>';

var city = '\
CA:AB:AI:Airdrie|\
CA:AB:BR:Brooks|\
//etc
';

var state = '\
US:AK:Alaska|\
US:AL:Alabama|\
US:AR:Arkansas|\
//etc
';

var country = '\
AF:Afghanistan|\
AL:Albania|\
DZ:Algeria|\
//etc
';

function TrimString(sInString) {
  if ( sInString ) {
    sInString = sInString.replace( /^\s+/g, "" );// strip leading
    return sInString.replace( /\s+$/g, "" );// strip trailing
  }
}

// Populates the country selected with the counties from the country list
function populateCountry(defaultCountry) {
  if ( postCountry != '' ) {
    defaultCountry = postCountry;
  }
  var countryLineArray = country.split('|');  // Split into lines
  var selObj = document.getElementById('countrySelect');
  selObj.options[0] = new Option('Select Country','');
  selObj.selectedIndex = 0;
  for (var loop = 0; loop < countryLineArray.length; loop++) {
    lineArray = countryLineArray[loop].split(':');
    countryCode  = TrimString(lineArray[0]);
    countryName  = TrimString(lineArray[1]);
    if ( countryCode != '' ) {
      selObj.options[loop + 1] = new Option(countryName, countryCode);
    }
    if ( defaultCountry == countryCode ) {
      selObj.selectedIndex = loop + 1;
    }
  }
}

function populateState() {
  var selObj = document.getElementById('stateSelect');
  var foundState = false;
  // Empty options just in case new drop down is shorter
  if ( selObj.type == 'select-one' ) {
    for (var i = 0; i < selObj.options.length; i++) {
      selObj.options[i] = null;
    }
    selObj.options.length=null;
    selObj.options[0] = new Option('Select State','');
    selObj.selectedIndex = 0;
  }
  // Populate the drop down with states from the selected country
  var stateLineArray = state.split("|");  // Split into lines
  var optionCntr = 1;
  for (var loop = 0; loop < stateLineArray.length; loop++) {
    lineArray = stateLineArray[loop].split(":");
    countryCode  = TrimString(lineArray[0]);
    stateCode    = TrimString(lineArray[1]);
    stateName    = TrimString(lineArray[2]);
  if (document.getElementById('countrySelect').value == countryCode && countryCode != '' ) {
    // If it's a input element, change it to a select
      if ( selObj.type == 'text' ) {
        parentObj = document.getElementById('stateSelect').parentNode;
        parentObj.removeChild(selObj);
        var inputSel = document.createElement("SELECT");
        inputSel.setAttribute("name","state");
        inputSel.setAttribute("id","stateSelect");
        parentObj.appendChild(inputSel);
        selObj = document.getElementById('stateSelect');
        selObj.options[0] = new Option('Select State','');
        selObj.selectedIndex = 0;
      }
      if ( stateCode != '' ) {
        selObj.options[optionCntr] = new Option(stateName, stateCode);
      }
      // See if it's selected from a previous post
      if ( stateCode == postState && countryCode == postCountry ) {
        selObj.selectedIndex = optionCntr;
      }
      foundState = true;
      optionCntr++
    }
  }
  // If the country has no states, change the select to a text box
  if ( ! foundState ) {
    parentObj = document.getElementById('stateSelect').parentNode;
    parentObj.removeChild(selObj);
  // Create the Input Field
    var inputEl = document.createElement("INPUT");
    inputEl.setAttribute("id", "stateSelect");
    inputEl.setAttribute("type", "text");
    inputEl.setAttribute("name", "state");
    inputEl.setAttribute("size", 20);
    inputEl.setAttribute("value", "");
    parentObj.appendChild(inputEl);
  }
}

function populateCity() {
var selObj = document.getElementById('citySelect');
  var foundCity = false;
  // Empty options just in case new drop down is shorter
  if ( selObj.type == 'select-one' ) {
    for (var i = 0; i < selObj.options.length; i++) {
      selObj.options[i] = null;
    }
    selObj.options.length=null;
    selObj.options[0] = new Option('Select City','');
    selObj.selectedIndex = 0;
  }
  
  var cityLineArray = city.split("|");  // Split into lines
  var optionCntr = 1;
  for (var loop = 0; loop < cityLineArray.length; loop++) {
    lineArray = cityLineArray[loop].split(":");
    countryCode  = TrimString(lineArray[0]);
    stateCode    = TrimString(lineArray[1]);
    cityCode    = TrimString(lineArray[2]);
    cityName    = TrimString(lineArray[3]);
  if (document.getElementById('stateSelect').value == stateCode && stateCode != '' ) {
    // If it's a input element, change it to a select
      if ( selObj.type == 'text' ) {
        parentObj = document.getElementById('citySelect').parentNode;
        parentObj.removeChild(selObj);
        var inputSel = document.createElement("SELECT");
        inputSel.setAttribute("name","city");
        inputSel.setAttribute("id","citySelect");
        parentObj.appendChild(inputSel);
        selObj = document.getElementById('citySelect');
        selObj.options[0] = new Option('Select City','');
        selObj.selectedIndex = 0;
      }
      if ( cityCode != '' ) {
        selObj.options[optionCntr] = new Option(cityName, cityCode);
      }
      // See if it's selected from a previous post
      if ( cityCode == postCity && stateCode == postState ) {
        selObj.selectedIndex = optionCntr;
      }
      foundCity = true;
      optionCntr++
    }
  }
  
  if ( ! foundCity ) {
    parentObj = document.getElementById('citySelect').parentNode;
    parentObj.removeChild(selObj);
  // Create the Input Field
    var inputEl = document.createElement("INPUT");
    inputEl.setAttribute("id", "citySelect");
    inputEl.setAttribute("type", "text");
    inputEl.setAttribute("name", "city");
    inputEl.setAttribute("size", 20);
    inputEl.setAttribute("value", "");
    parentObj.appendChild(inputEl);
  }
}
function initCountry(country) {
  populateCountry(country);
  populateState();
  populateCity();
}

all that is in list.js and in my php form I have <script type="text/javascript" src="list.js"></script>
and for the drop down lists

<select id='countrySelect' name='country' onchange='populateState()'></select>

<select id='stateSelect' name='state'></select>
<script type="text/javascript">initCountry('CA'); </script>

<select id='citySelect' name='city'></select>

any ideas what I'm doing wrong?

any help would be greatly appreciated!



#2 Kris

Kris
  • Staff Alumni
  • Advanced Member
  • 2,755 posts
  • LocationThe Internet

Posted 25 April 2006 - 08:20 AM

Please don't post JavaScript questions in the PHP forums.
Moved.

#3 GBS

GBS
  • Members
  • PipPipPip
  • Advanced Member
  • 108 posts

Posted 25 April 2006 - 02:17 PM

Hi there,,

Tested that one,, & it seems OK to me with both IE & FF,
main file is about:
<html>
<body>
<select id='countrySelect' name='country' onchange='populateState()'></select>
<select id='stateSelect' name='state' disabled=true onchange='populateCity()'></select>
<select id='citySelect' name='city' disabled=true></select>
<script type="text/javascript" src="list.js"></script>
<script type="text/javascript">initCountry('CA'); </script>
</body>
</html>
& the list.js file:
var postState = '<?= $_POST["state"] ?>';
var postCountry = '<?= $_POST["country"] ?>';
var postCity = '<?= $_POST["city"] ?>';

var city = '\
CA:AB:AI:Airdrie|\
CA:AB:BR:Brooks|\
AL:TE:TE:testing1|\
US:AK:BR:Brooks|\
';

var state = '\
US:AK:Alaska|\
US:AL:Alabama|\
US:AR:Arkansas|\
AL:TE:testing2|\
';

var country = '\
AF:Afghanistan|\
AL:Albania|\
DZ:Algeria|\
US:Usa|\
';

function TrimString(sInString)
{
if ( sInString )
    {
    sInString = sInString.replace( /^\s+/g, "" );// strip leading
    return sInString.replace( /\s+$/g, "" );// strip trailing
    }
}

// Populates the country selected with the counties from the country list
function populateCountry(defaultCountry)
{
if ( postCountry != '' )
    {
    defaultCountry = postCountry;
    }
var countryLineArray = country.split('|');  // Split into lines
var selObj = document.getElementById('countrySelect');
selObj.options[0] = new Option('Select Country','');
selObj.selectedIndex = 0;
for (var loop = 0; loop < countryLineArray.length-1; loop++)
    {
    lineArray = countryLineArray[loop].split(':');
    countryCode  = TrimString(lineArray[0]);
    countryName  = TrimString(lineArray[1]);
    if ( countryCode != '' )
        {
        selObj.options[loop + 1] = new Option(countryName, countryCode);
        }
    if ( defaultCountry == countryCode )
        {
        selObj.selectedIndex = loop + 1;
        }
    }
}

function populateState() {
// we make states & city selects disabled for now
document.getElementById('stateSelect').selectedIndex=0;
document.getElementById('stateSelect').disabled=true;
document.getElementById('citySelect').selectedIndex=0;
document.getElementById('citySelect').disabled=true;


if (document.getElementById('countrySelect').selectedIndex>0)
    {
    var selObj = document.getElementById('stateSelect');
    var foundState = false;
    var defaultstate ="";
    // Empty options just in case new drop down is shorter
    if ( selObj.type == 'select-one' )
        {
        for (var i = 0; i < selObj.options.length; i++)
            {
            selObj.options[i] = null;
            }
        selObj.options.length=null;
        selObj.options[0] = new Option('Select State','');
        selObj.selectedIndex = 0;
        }


    // Populate the drop down with states from the selected country
    var stateLineArray = state.split("|");  // Split into lines
    var optionCntr = 1;
    for (var loop = 0; loop < stateLineArray.length; loop++)
        {
        lineArray = stateLineArray[loop].split(":");
        countryCode  = TrimString(lineArray[0]);
        stateCode    = TrimString(lineArray[1]);
        stateName    = TrimString(lineArray[2]);
        if (document.getElementById('countrySelect').value == countryCode && countryCode != '' )
            {
            if ( stateCode != '' )
                {
                selObj.options[optionCntr] = new Option(stateName, stateCode);
                // as we have some value, we enable the select object
                document.getElementById('stateSelect').disabled=false;
                }
            // See if it's selected from a previous post
            if ( stateCode == postState && countryCode == postCountry )
                {
                selObj.selectedIndex = optionCntr;
                }
                foundState = true;
                optionCntr++
            }
        }
    }

if ( !foundState )
    {
    var selObj = document.getElementById('stateSelect');
    selObj.options[0] = new Option('Select State','');
    selObj.selectedIndex = 0;
    }
}

function populateCity() {

document.getElementById('citySelect').selectedIndex=0;
document.getElementById('citySelect').disabled=true;

if (document.getElementById('stateSelect').selectedIndex>0)
    {

    var selObj = document.getElementById('citySelect');
    var foundCity = false;
    // Empty options just in case new drop down is shorter
    if ( selObj.type == 'select-one' )
        {
        for (var i = 0; i < selObj.options.length; i++)
            {
            selObj.options[i] = null;
            }
        selObj.options.length=null;
        selObj.options[0] = new Option('Select City','');
        selObj.selectedIndex = 0;
        }
  
    var cityLineArray = city.split("|");  // Split into lines
    var optionCntr = 1;
    for (var loop = 0; loop < cityLineArray.length; loop++)
        {
        lineArray = cityLineArray[loop].split(":");
        countryCode  = TrimString(lineArray[0]);
        stateCode    = TrimString(lineArray[1]);
        cityCode    = TrimString(lineArray[2]);
        cityName    = TrimString(lineArray[3]);
        if (document.getElementById('stateSelect').value == stateCode && stateCode != '' )
            {
            if ( cityCode != '' )
                {
                selObj.options[optionCntr] = new Option(cityName, cityCode);
                // as we have some value, we enable the select object
                document.getElementById('citySelect').disabled=false;
                }
            // See if it's selected from a previous post
            if ( cityCode == postCity && stateCode == postState )
                {
                selObj.selectedIndex = optionCntr;
                }
            foundCity = true;
            optionCntr++
            }
        }
    }
  
if ( !foundCity )
    {
    var selObj = document.getElementById('citySelect');
    selObj.options[0] = new Option('Select City','');
    selObj.selectedIndex = 0;
    }
}
function initCountry(country) {
  populateCountry(country);
  populateState();
  populateCity();
}
I made few changes in the js part,... hoping it helps,,

l8tr,,
Sorry for my english,... I do my best, but sometimes,...
1st intention: understand the problem
2nd intention: try to solve it
3rd intention: try to understand how to solve it :)

#4 digitalgod

digitalgod
  • Members
  • PipPipPip
  • Advanced Member
  • 374 posts

Posted 25 April 2006 - 03:41 PM

Please don't post JavaScript questions in the PHP forums.
Moved.


sorry about that was very late and I was tired :S

I made few changes in the js part,... hoping it helps,,


thanks man :D! it works perfectly. Can you please explain to me what made it work so I can understand :P

#5 GBS

GBS
  • Members
  • PipPipPip
  • Advanced Member
  • 108 posts

Posted 25 April 2006 - 05:02 PM

sure,, np,, :)
In your html part, it was:
<select id='countrySelect' name='country' onchange='populateState()'></select>
<select id='stateSelect' name='state' ></select>
So, once the choice was made in the State select object, there were none query to populate the city select object,
changes made:
[!--quoteo--][div class=\'quotetop\']QUOTE[/div][div class=\'quotemain\'][!--quotec--]
<select id='stateSelect' name='state' disabled=true onchange='populateCity()'></select>
[/quote]
After, in the js part, I have used the 'selectedIndex' & 'disabled' properties, to make the elements enabled or not, like:
document.getElementById('citySelect').selectedIndex=0; // set the index selected to 0, ('Select City', for this case)
document.getElementById('citySelect').disabled=true; // disable the City select object, until it's populated
So,, once a value was found to populate the select object, we add the line to enable the select object,, by example:
[!--quoteo--][div class=\'quotetop\']QUOTE[/div][div class=\'quotemain\'][!--quotec--]
if ( stateCode != '' )
{
selObj.options[optionCntr] = new Option(stateName, stateCode);
// as we have some value, we enable the select object
document.getElementById('stateSelect').disabled=false;
}
[/quote]
I've removed the lines about "if ( selObj.type == 'text' )" ,, they were no more needed,,
& at least, I have changes the kind of lines:
  if ( ! foundCity ) {
    parentObj = document.getElementById('citySelect').parentNode;
    parentObj.removeChild(selObj);
  // Create the Input Field
    var inputEl = document.createElement("INPUT");
    inputEl.setAttribute("id", "citySelect");
    inputEl.setAttribute("type", "text");
    inputEl.setAttribute("name", "city");
    inputEl.setAttribute("size", 20);
    inputEl.setAttribute("value", "");
    parentObj.appendChild(inputEl);
  }
into:
  if ( ! foundCity ) {
    var selObj = document.getElementById('citySelect');
    selObj.options[0] = new Option('Select City','');
    selObj.selectedIndex = 0;
 }
to initiate the City & State select objects,

Happy script,,

l8tr,,
Sorry for my english,... I do my best, but sometimes,...
1st intention: understand the problem
2nd intention: try to solve it
3rd intention: try to understand how to solve it :)

#6 digitalgod

digitalgod
  • Members
  • PipPipPip
  • Advanced Member
  • 374 posts

Posted 25 April 2006 - 05:08 PM

thanks GBS

what's weird was that I did have a onchange = 'populateCity()' before but that didn't work at all, all 3 drop downs were empty when I did that.

thanks for your help :)

#7 GBS

GBS
  • Members
  • PipPipPip
  • Advanced Member
  • 108 posts

Posted 25 April 2006 - 05:21 PM

yep,, some lines like:
parentObj.removeChild(selObj);
were doing strange things into your original script,,

glad to have helped,,

l8tr,, ;)
Sorry for my english,... I do my best, but sometimes,...
1st intention: understand the problem
2nd intention: try to solve it
3rd intention: try to understand how to solve it :)




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users