Jump to content

Recommended Posts

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....

[code]
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();
}
[/code]

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!

Link to comment
https://forums.phpfreaks.com/topic/8347-dynamic-drop-down-lists/
Share on other sites

Hi there,,

Tested that one,, & it seems OK to me with both IE & FF,
main file is about:
[code]
<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>
[/code]
& the list.js file:
[code]
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();
}
[/code]
I made few changes in the js part,... hoping it helps,,

l8tr,,
Link to comment
https://forums.phpfreaks.com/topic/8347-dynamic-drop-down-lists/#findComment-30559
Share on other sites

[quote]Please don't post JavaScript questions in the PHP forums.
Moved.[/quote]

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

[quote]I made few changes in the js part,... hoping it helps,,[/quote]

thanks man :D! it works perfectly. Can you please explain to me what made it work so I can understand :P
Link to comment
https://forums.phpfreaks.com/topic/8347-dynamic-drop-down-lists/#findComment-30608
Share on other sites

sure,, np,, :)
In your html part, it was:
[code]
<select id='countrySelect' name='country' onchange='populateState()'></select>
<select id='stateSelect' name='state' ></select>
[/code]
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 [b]onchange='populateCity()'[/b]></select>
[/quote]
After, in the js part, I have used the 'selectedIndex' & 'disabled' properties, to make the elements enabled or not, like:
[code]
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
[/code]
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
[b]document.getElementById('stateSelect').disabled=false;[/b]
}
[/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:
[code]
  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);
  }
[/code]
into:
[code]
  if ( ! foundCity ) {
    var selObj = document.getElementById('citySelect');
    selObj.options[0] = new Option('Select City','');
    selObj.selectedIndex = 0;
}
[/code]
to initiate the City & State select objects,

Happy script,,

l8tr,,
Link to comment
https://forums.phpfreaks.com/topic/8347-dynamic-drop-down-lists/#findComment-30632
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.