简体   繁体   中英

How to keep the selected onchange dropdown list value after submit

I have three dropdown list which is country,state and city. At first, the country dropdown would be displayed with all countries. When a country would be chosen, the respective states would be fetched from the MySQL database and appear in the states dropdown. Alike when a state would be chosen, the respective cities will be fetched from the MySQL database and appear in the cities dropdown.

Below is the default display before I select country,state,city and click submit button.

在此处输入图像描述

After I select country, state, city and click submit button like below. It will refresh and go back to the default display.

在此处输入图像描述

So how can I keep the selected value(United Kingdom,England,London) display in the dropdown list instead it jump back to default display after clicked submit button?

Index.php

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<style type="text/css">
.select-boxes{width: 280px;text-align: center;}

</style>
<script src="jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#country').on('change',function(){
    var countryID = $(this).val();
    if(countryID){
        $.ajax({
            type:'POST',
            url:'ajaxData.php',
            data:'country_id='+countryID,
            success:function(html){
                $('#state').html(html);
                $('#city').html('<option value="">Select state first</option>'); 
            }
        }); 
    }else{
        $('#state').html('<option value="">Select country first</option>');
        $('#city').html('<option value="">Select state first</option>'); 
    }
});

$('#state').on('change',function(){
    var stateID = $(this).val();
    if(stateID){
        $.ajax({
            type:'POST',
            url:'ajaxData.php',
            data:'state_id='+stateID,
            success:function(html){
                $('#city').html(html);
            }
        }); 
    }else{
        $('#city').html('<option value="">Select state first</option>'); 
    }
});
});
</script>
</head>
<body>
<form id="form1" name="form1" method="get" action="<?php echo     $_SERVER['PHP_SELF'];?>">
<?php
//Include database configuration file
include('dbConfig.php');

//Get all country data
$query = $db->query("SELECT * FROM countries WHERE status = 1 ORDER BY country_name ASC");

//Count total number of rows
$rowCount = $query->num_rows;
?>
<select  name="country" id="country">
    <option value="">Select Country</option>
    <?php
    if($rowCount > 0){
        while($row = $query->fetch_assoc()){ 
            echo '<option value="'.$row['country_id'].'">'.$row['country_name'].'</option>';
        }
    }else{
        echo '<option value="">Country not available</option>';
    }
    ?>
</select>

<select  name="state" id="state">
    <option value="">Select country first</option>
</select>

<select  name="city" id="city">
    <option value="">Select state first</option>
</select>
<input type="submit" name="Submit" id="Submit" value="Submit" />
</form>
</body>
</html>

ajaxData.php

<?php
//Include database configuration file
include('dbConfig.php');

if(isset($_POST["country_id"]) && !empty($_POST["country_id"])){
//Get all state data

$query = $db->query("SELECT * FROM states WHERE country_id IN (".$_POST['country_id'].")");

//Count total number of rows
$rowCount = $query->num_rows;

//Display states list
if($rowCount > 0){
    echo '<option value="">Select state</option>';
    while($row = $query->fetch_assoc()){ 
        echo '<option value="'.$row['state_id'].'">'.$row['state_name'].'</option>';
    }
}else{
    echo '<option value="">State not available</option>';
}
}

if(isset($_POST["state_id"]) && !empty($_POST["state_id"])){
//Get all city data
$query = $db->query("SELECT * FROM cities WHERE state_id IN(".$_POST["state_id"].")");

//Count total number of rows
$rowCount = $query->num_rows;

//Display cities list
if($rowCount > 0){
    echo '<option value="">Select city</option>';
    while($row = $query->fetch_assoc()){ 
        echo '<option value="'.$row['city_id'].'">'.$row['city_name'].'</option>';
    }
}else{
    echo '<option value="">City not available</option>';
}
}
?>

dbConfig.php

<?php
//db details
$dbHost = 'localhost';
$dbUsername = 'root';
$dbPassword = '';
$dbName = 'location_db';

//Connect and select the database
$db = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName);

if ($db->connect_error) {
die("Connection failed: " . $db->connect_error);
}
?>

Firstly do this:

<select  name="country" id="country">
    <option value="">Select Country</option>
    <?php
    $selectedCountry = filter_input(INPUT_POST, "country"); 
    if($rowCount > 0){
        while($row = $query->fetch_assoc()){ 
            echo '<option value="'.$row['country_id'].'" '.($selectedCountry==$row['country_id']?"selected='selected'":"").'>'.$row['country_name'].'</option>';
        }
    }else{
        echo '<option value="">Country not available</option>';
    }
    ?>
</select>

Then on your document ready event do:

<script type="text/javascript">
$(document).ready(function(){
$("#country").one("finishedLoading", function () {
      setTimeout(function () {$("#state").val("<?= (filter_input(INPUT_POST,"state")?:"[]") ?>").trigger("change")},10);
});
 $("#state").one("finishedLoadingState", function () {
      setTimeout(function () { $("#city").val("<?= (filter_input(INPUT_POST,"city")?:"[]") ?>").trigger("change") }, 10);
});

$('#country').on('change',function(){
    var countryID = $(this).val();
    if(countryID){
        $.ajax({
            type:'POST',
            url:'ajaxData.php',
            data:'country_id='+countryID,
            success:function(html){
                $('#state').html(html);
                $('#city').html('<option value="">Select state first</option>'); 
                $("#country").trigger("finishedLoading"); //Little custom event we can listen for
            }
        }); 
    }else{
        $('#state').html('<option value="">Select country first</option>');
        $('#city').html('<option value="">Select state first</option>'); 
        $("#country").trigget("finishedLoading");
    }
}).trigger("change"); //Trigger immediately in case there's a value pre-selected 
$('#state').on('change',function(){
    var stateID = $(this).val();
    if(stateID){
        $.ajax({
            type:'POST',
            url:'ajaxData.php',
            data:'state_id='+stateID,
            success:function(html){
                $('#city').html(html);
                $("#state").trigger("finishedLoadingState");
            }
        }); 
    }else{
        $('#city').html('<option value="">Select state first</option>'); 
        $("#state").trigger("finishedLoadingState");
    }
});

The idea is you chain trigger the "change" events the same way a user might.

you can do it using hidden filed

<input type="hidden" name="selectedoption" value="<?php echo !empty($_POST['selectedoption']) ? strip_tags($_POST['selectedoption']) : ''; ?>" />




<select id="sortSelect" class="selctedcls" size="1" name="selectedoption" onchange="this.form.submit();" >
                <option selected>value1</option>
                <option value="value2">value2</option>
                <option value="value3">value3</option>
                <option value="value4">value4</option>
        </select> 

<script type="text/javascript">
document.getElementById('selctedcls').value ="<?php if(! $_POST['selectedoption']):?>"selectedoption"<?php  else:  echo $_POST['selectedoption']; endif;?>";
</script>

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