-1

So I have a select tag that is using a loop in order to populate itself with options from a database. Once an option is selected the page reloads and creates a table based on the city selected, which all works as intended.

<div class="col-sm-2">
        <select name="city" id="city" class="form-control" tabindex="5" placeholder="Select City">
            <option value="" disabled selected>Select City</option>
            <?php
            foreach($cities as $key=>$val)
                echo "<option value={$key}>{$val}</option>";
            ?>
        </select>
    </div>
    <div class="col-sm-2">
        <input type="submit" name="Create City" class="btn btn-primary pull-left" />
    </div>

My question is how would I have the selector display the chosen option after the page is reloaded?

Friday
  • 1
  • 1
    Hi, you need to add the `selected` attribute to the ` – Ermac Mar 23 '20 at 12:19
  • Please read the existing questions before creating a new one. https://stackoverflow.com/questions/47220065/php-select-selected-not-working – Sasikumar Mar 23 '20 at 12:39
  • Does this answer your question? [Php select=selected not working](https://stackoverflow.com/questions/47220065/php-select-selected-not-working) – Grant Fritchey Mar 23 '20 at 13:07

1 Answers1

1

You need to check that the value in $_POST['city'] is the one in the current occurance and if it is add a selected to this option tag

<div class="col-sm-2">
    <select name="city" id="city" class="form-control" tabindex="5" placeholder="Select City">
        <option value="" disabled >Select City</option>
<?php
    foreach($cities as $key=>$val) {
        $sel = '';
        if ( $_POST['city'] == $key ) { 
            $sel = 'selected'; 
        }
        echo "<option $sel value={$key}>{$val}</option>";
    }
?>
    </select>
</div>
<div class="col-sm-2">
    <input type="submit" name="Create City" class="btn btn-primary pull-left" />
</div>
RiggsFolly
  • 93,638
  • 21
  • 103
  • 149