Question

this is my code for dropdown list,plz guide me.

<div class = "form-inline">
  <label class = "">Situation</label>
  <select selected="" name="sit" id="situ" class='form-control'style="margin-left: 30px; width: 145px;">
    <option value="" >select</option>
    <?
    if ($situation != '') {
    $revise = $situation;
    }
    foreach ($revise as $row):
    ?>
    <option value="<?= $row['id']; ?>"><?= $row['situation']; ?></option>
    <? endforeach; ?>
  </select>
</div>
Was it helpful?

Solution

For the item you want selected for a dropdown list, add the attribute selected.

Eg.

<select>
  <option value="0">0</option>
  <option value="1" selected="selected">1</option>
  <option value="2">2</option>
</select>

In this case, 1 will be selected.

To get the value of this dropdown after form submit, it depends on the method of your form being POST or GET.

In this example, I'm assuming it's POST. <form method="POST">

<div class = "form-inline">
  <label class = "">Situation</label>
  <select selected="" name="sit" id="situ" class='form-control'style="margin-left: 30px; width: 145px;">
    <option value="" >select</option>
    <?
    if (isset($_POST['sit']))
        $selected = $_POST['sit'];
    if ($situation != '') {
    $revise = $situation;
    }
    foreach ($revise as $row):
        $selectedHTML = '';
        if (isset($selected) && $row['id'] == $selected)
            $selectedHTML = ' selected="selected"';
    ?>
    <option value="<?= $row['id']; ?>"<?= $selectedHTML; ?>><?= $row['situation']; ?></option>
    <? endforeach; ?>
  </select>
</div>

You can try something like this.

if (isset($_POST['sit']))
  $selected = $_POST['sit'];

What this does is check if $_POST['sit'] value is found. If yes then we'll make that $selected, else we'll leave it.

$selectedHTML = '';
if (isset($selected) && $row['id'] == $selected)
  $selectedHTML = ' selected="selected"';

And then in the foreach loop, we will first initialize $selectedHTML as empty string. It will not add anything to <option> unless it got its value changed.

We will check if $selected is defined or not and if it is, we will check if the current value of $row['id'] within the foreach loop is equal to the submitted value which is $selected. If so, we will set $selectedHTML which will add selected="selected" only to the current <option>.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top