3

I am trying to set selected in <option> tag.

What is wrong with my code?

My Code is:

<select required  name="site-list"   class="form-control" style="margin: 9px 0px 0px 0px;">

<option value="">Select</option>  

<?php foreach($MLCSites as $site) { ?>

<option id="emp"  value="<?php echo $site->site_key;?>" <?php if($site->id == $site->site_key){ echo "selected";}   ?>><?php echo $site->site_name;?></option>
      <?php } ?>

 </select>

Genrated HTML:

<select required="" name="site-list" id="site-list" class="form-control" style="margin: 9px 0px 0px 0px;">        
<option value="">Select  Site</option>  
<option value="HT45-YT6T">bizRTC</option>
<option value="EB22-0309">RTCBiz</option>
</select>

What should be my comparison to set selected = selected ??

Table:

Tables

Rajan
  • 2,427
  • 10
  • 51
  • 111

2 Answers2

3

You should use 'selected=selected' and to avoids error, remove id="emp", because id is for one value

foreach ($MLCSites as $site) : ?>

    <option value="<?= $site->site_key; ?>"
        <?php if ($site->id == $site->site_key) :
            echo "selected=selected";
        endif; ?>>
        <?= $site->site_name; ?>
    </option>
<?php endforeach; ?>
callmemath
  • 8,185
  • 4
  • 37
  • 50
0
.
.
.

if($site->id == $site->site_key){ echo ' selected="selected"';}

.
.
.
Amir
  • 4,089
  • 4
  • 16
  • 28
  • While this code may answer the question, it would be better to include some context, explaining how it works and when to use it. Code-only answers are not useful in the long run. – Bono Apr 18 '16 at 09:28
  • @Bono, I just changed user code from `'selected'` to `'selected="selected"'`. It was only a syntax problem.Most of the time simplicity is better – Amir Apr 18 '16 at 10:03