Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 3850712
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 19, 20262026-05-19T17:03:07+00:00 2026-05-19T17:03:07+00:00

Here’s the issue: I have a JS dropdown for country and state that runs

  • 0

Here’s the issue: I have a JS dropdown for country and state that runs in a PHP form for users to update their profiles.

The user selects country for ex ‘USA’, then state ‘Colorado’, and submits. What happens is that these values are saved OK on my database, but when the page refreshes, only the country dropdown remains selected with the user’s choice. The state shows as ‘Select State’, although the value ‘Colorado’ is in the DB.

I just can’t manage to have PHP and JS talk to each other so that if the user chose Colorado, it should be pulled from the DB and shown as selected whenever they refresh or come back to the page.

Any ideas how to do this? I tried the suggestion at the top of the JS code but was unsuccessful.

Here is the JS (some code trimmed for brevity):

// If you have PHP you can set the post values like this
//var postState = '<?= $_POST["state"] ?>';
//var postCountry = '<?= $_POST["country"] ?>';
var postState = '';
var postCountry = '';

// To edit the list, just delete a line or add a line. Order is important.
// The order displayed here is the order it appears on the drop down.
//
var state = '\
US:Alaska:Alaska|\
US:Alabama:Alabama|\
';

var country = '\
US:United States|\
CA:Canada|\
';

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", 30);
    inputEl.setAttribute("value", postState);
    parentObj.appendChild(inputEl) ;
  }
}

function initCountry(country) {
  populateCountry(country);
  populateState();
}

and here is the PHP/HTML (trimmed a bit):

<?php
include 'dbc.php';
page_protect();

$err = array();
$msg = array();

if ($_POST['doUpdate'] == 'Update') {

    foreach ($_POST as $key => $value) {
        $data[$key] = filter($value);
    }

    $country =          $data['country'];
    $state =            $data['state'];

    mysql_query("UPDATE users SET
    `country` =         '$data[country]',
    `state` =           '$data[state]'

     WHERE id='$_SESSION[user_id]'
    ") or die(mysql_error());

    $msg[] = "Your Profile has been updated";
    //header("Location: mysettings.php?msg=Your new password is updated");

}

$rs_settings = mysql_query("select * from users where id='$_SESSION[user_id]'");
?>

<html>
<body>
    <form name="profile_form" id="profile_form" method="post" action="">
        <?php while ($row_settings = mysql_fetch_array($rs_settings)) {?>
        <input name="doUpdate" type="submit" id="doUpdate" value="Update">

        <table>
            <tr>
                <th>Country:</th>

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

            <tr>
                <th>State:</th>

                <td>
                    <select id='stateSelect' name='state'>
                    </select> 
                        <script type="text/javascript">
                            initCountry('<?php echo $row_settings['country']; ?>'); 
                    </script>
                </td>
            </tr>
        </table>
    </form>
</body>
</html>
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-19T17:03:08+00:00Added an answer on May 19, 2026 at 5:03 pm

    One of the issues i often run into with Javascript is the load order.

    You appear to be running and calling populateCountry and populateState at the same time, thereby not having much opportunity for the State list to be populated once the country list has been determined.

    Consider moving “populateState()” to the last line of “populateCountry()” so it calls it at the end of the function processing.

    There are multiple ways to do this, but this is the simplest to illustrate the point.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Here is the issue I am having: I have a large query that needs
Here is the problem that I am trying to solve. I have two folders
Here is my code (Say we have a single button on the page that
Here's a problem I ran into recently. I have attributes strings of the form
Here's my scenario - I have an SSIS job that depends on another prior
Here is what I am trying to achieve in PHP: I have this string:
Here is my scenario. I have a website running under AppPool1 and that works
Here's the code I have. It works. The only problem is that the first
Here is what I am currently doing. PHP echo's out the recent post in
Here is the Javascript I currently have <script type=text/javascript> $(function() { $('.slideshow').hover( function() {

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.