Ben
Ben

Reputation: 393

Option value Not displaying in drop-down menu?

I'm using a date range on a web page to aggregate MySQL data and present it based on the selected time frame. For some reason the values for each option in the drop-down menus are not displaying. Here's the PHP I'm using:

<select name="date1" title="<?=$date1 ?>">
<?php foreach($availableDates as $date) { ?>
<option value="<?=$date ?>"<?php if($date == $date1) { ?> selected="selected"<?php } ?><?=$date ?></option>
<?php } ?>
</select>

And here's the HTML output:

<option value="2015-01-03" selected="selected" 2015-01-03<="" option=""></option>

The weirdest part is this was working for the longest time and suddenly the dates in both menus vanished. Any ideas why?

Upvotes: 1

Views: 1263

Answers (5)

mplungjan
mplungjan

Reputation: 178411

I suggest this less error prone code.

$selHTML = '<select name="date1" title="'.$date1.'">';
foreach($availableDates as $date) { 
  $sel = ($date == $date1)?" selected":"";
  $selHTML .= '<option value="'.$date.'"'.$sel.'>'.$date.'</option>';
}
$selHTML .= '</select>';
echo $selHTML;

Upvotes: 0

AddWeb Solution Pvt Ltd
AddWeb Solution Pvt Ltd

Reputation: 21691

1. Add > tag closer after selected attribute
2. Remove shorthanded <?= ?> tag which is unwanted while you also using <?php ?>

<select name="date1" title="<?php print $date1; ?>">
    <?php foreach($availableDates as $date) { 
        ?><option value="<?php print $date; ?>"<?php if($date == $date1) { ?> selected="selected"<?php } ?>>
            <?php print $date; ?>
        </option>
    <?php } ?>
</select>

Upvotes: 1

Amitesh Kumar
Amitesh Kumar

Reputation: 3079

Try this way also :

<select name="per1" id="per1">
  <option selected="selected">Choose one</option>
  <?php
    foreach($names as $name) { ?>
      <option value="<?= $name['name'] ?>"><?= $name['name'] ?></option>
  <?php
    } ?>
</select> 

Now you can put your code here.

Upvotes: 1

Brett DeWoody
Brett DeWoody

Reputation: 62881

Your PHP snippet is missing a closing >:

<select name="date1" title="<?=$date1 ?>">
  <?php foreach($availableDates as $date) { ?>
  <option 
    value="<?=$date ?>"
    <?php if($date == $date1) { ?> selected="selected"<?php } ?>
  >
    <?=$date ?>
  </option>
  <?php } ?>
</select>

Upvotes: 1

devpro
devpro

Reputation: 16117

This happened becuase you are missing the ending > of tag

Modified code:

<select name="date1" title="<?=$date1 ?>">
<?php foreach($availableDates as $date) { ?>
<option value="<?=$date ?>"<?php if($date == $date1) { ?> selected="selected"<?php } ?>>
<?=$date ?>
</option>
<?php } ?>
</select>

Upvotes: 1

Related Questions