简体   繁体   中英

How to keep selected value after submit in php

Below is the code where only two options are there in dropdown list ie 2016 and 2017. I want to keep selected value after submit. But im getting 2016 after selecting 2017. What changes need to be done?

<?php
$yearArray = range(2016, 2017);
?>

<select name="year" id="select2">
<option value="0">Select Year</option>
<?php
foreach ($yearArray as $year)
{

    $selected = ( $year == 2016) ? 'selected' : '';
    echo '<option name="year" '.$selected.'  value="'.$year.'">'.$year.'</option>';
}
?>
</select>

Try this:

if((isset($_POST['year']) && $year == $_POST['year'])){
    $selected = 'selected';
 }else if($year == 2016){
   $selected = 'selected';
}

The reason why 2016 is selected always is because you are setting it to 2016.

<?php
foreach ($yearArray as $year)
{

    $selected = ( $year == 2016) ? 'selected' : ''; // Here, you are setting it 
    echo '<option name="year" '.$selected.'  value="'.$year.'">'.$year.'</option>';
}
?>

Instead do this,

<?php
foreach ($yearArray as $year)
{

    $selected = ((isset($_POST['year']) && $_POST['year'] == $year) || ($year == '2016')) ? 'selected' : '';

    echo '<option name="year" '.$selected.'  value="'.$year.'">'.$year.'</option>';
}
?>

By default 2016 is selected, if you have submitted any other value, that will be selected.

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