简体   繁体   中英

Populate the values of select boxes dynamically from another select box

I have two select options of Countries and States . The option values are populating from database using php functions. I would like to populate the States depending on the selection of Countries . For example, if I select US from Countries then States select option will populate me all the States belongs to the US Country.

Here is my code -

<select id="countryName" name="countryName" onChange="getCountryCode()">
    <option value=""></option>
    <?php $countries = $location->getCountries();
         foreach ($countries as $country) {
             echo '<option value="' . $country->id . '">' . $country->name . '</option>';
         }
    ?>                                        
</select>

I can get the selected country value using javascript function

<script type="text/javascript">
     function getCountryCode(){
         var countryCode = document.getElementById('countryName').value;
     }
</script>

After all these, I am trying to get the States of selected Country using the php function getStates($countryCode) . But I don't know how to pass the javascript variable to php function.

<select name="stateName">
     <option value=""></option>
     <?php $states = $location->getStates($countryCode);
          foreach ($states as $state) {
              echo '<option value="' . $state->id . '">' . $state->name . '</option>';
          }
     ?>
</select>

Does anyone have any idea how do I pass the javascript variable to php or if have better idea than this, please do share.

Thank you!

Currently you mix JavaScript code (client side) with PHP code (server side). That's not possible that way. After you send your content to the browser, php has to wait, till the user takes some action which calls the server again. In your case, there are two possible solutions.

  1. Use AJAX to get the content of the state select box from the server. One way could be a simple php script, which just prints the states:

PHP Script

$states = $location->getStates($_GET['state']);
foreach ($states as $state) {
    echo '<option value="' . $state->id . '">' . $state->name . '</option>';
}

Javascript (using jQuery)

$('#countryName').on('change', function() {
    $.ajax({
        url: 'states.php',
        data: { state: $(this).val() },
        type: 'GET',
        success: function(data) {
            $('select[name="stateName"]').html(data);
        }
    });
});
  1. Another solution without ajax would be to print always all states and show/hide them in relation to the value of your country select box

PHP script

$states = $location->getAllStates();
foreach ($states as $state) {
    echo '<option data-country="{$state->country}" value="{$state->id}">{$state->name}</option>';
}

JavaScript (using jQuery)

$(function() {
    var $statesSelect = $('select[name="stateName"]');
    var $states = $('option', $statesSelect);
    // first remove all elements from dom
    $states.detach();
    // and then listen to change event and show/hide them
    $('#countryName').on('change', function() {
        var val = $(this).val();
        $('option', $statesSelect).detach();
        $states.each(function() {
            $(this).is('[data-country="' + val + '"').appendTo($statesSelect);
        });
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM