使用PHP操作“selected”选项

时间:2015-01-19 16:09:47

标签: php html

我正在创建一个相当基本的表单,我的一个要求是检查并查看值是否在提交时有效,如果是,但是其他不是,它们应该默认为原始值。出于某种原因,无论单击哪个选项,我都会将选项中的最后一个值设置为选中状态。在某个地方可能是一个明显的错误,我似乎无法看到它。这是代码。

<select name="degree">
<option value="" selected="<?php if ($_GET['degree'] === "false"){echo "selected";}?>">Select a Major</option>
<option value="Arts" selected="<?php if($_GET['degree'] === "Arts"){echo "selected";}
else{echo "false";}?>">Arts</option>
<option value="Science" selected="<?php if($_GET['degree'] === "Science"){echo "selected";}
else{echo "false";}?>">Science</option>
<option value="Commerce" selected="<?php if($_GET['degree'] === "Commerce"){echo "selected";}
else{echo "false";}?>">Commerce</option>
<option value="Economics" selected="<?php if($_GET['degree'] === "Economics"){echo "selected";}
else{echo "false";}?>">Economics</option>
<option value="Engineering" selected="<?php if($_GET['degree'] === "Engineering"){echo "selected";}
else{echo "false";}?>">Engineering</option>
<option value="Computer Science" selected="<?php if($_GET['degree'] === "Computer Science"){echo "selected";}
else{echo "false";}?>">Computer Science</option>
<option value="Music" selected="<?php if($_GET['degree'] === "Music"){echo "selected";}
else{echo "false";}?>">Music</option>
<option value="Business" selected="<?php if($_GET['degree'] === "Business"){echo "selected";}
else{echo "false";}?>">Business</option>
</select>

2 个答案:

答案 0 :(得分:2)

你的问题是HTML,而不是php。实际上,当选项具有属性selected时,选择该选项,与其值无关。

<option selected><option selected="selected"><option selected="false">都已被选中。仅未选择<option>

因此你需要改变:

<option value="Arts"<?php if($_GET['degree'] === "Arts"){echo ' selected="selected"';}?>">Arts</option>

现在关于风格

  • Do not repeat yourself(DRY)
  • 缩进代码
  • 并且特别针对PHP:在PHP和HTML之间不要经常更改。

这看起来有点干净:

echo '<select name="degree">';
$options = array(
    'Select a Major' => '',
    'Science' => 'Science',
    ...
);
foreach($options as $display => $value){
    echo '<option value="'.$value.'"';
    if($_GET['degree'] == $value) echo 'selected="selected"';
    echo '>'.$display.'</option>';
}
echo '</select>';

答案 1 :(得分:0)

你应该写一个函数告诉你选择哪个选项&#34;选择&#34;

<?php 
function isOptSelected($opt){
    return ($_GET['degree'] == $opt)? ' selected="selected"': '';
}
?>

进一步在HTML代码中:

<select name="degree">
<option value="" <?php echo isOptSelected('');?> >Select a Major</option>
<option value="Arts"  <?php echo isOptSelected('Arts');?> >Arts</option>
<option value="Science"  <?php echo isOptSelected('Science');?> >Arts</option>
...