php 在 <SELECT> 中选择动态默认值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7571710/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Selecting dynamic default value in <SELECT>
提问by Varun Kumar
I have a php script which updates user info. I have created an html form, which allows user to edit the values and enter new ones. Now when the form is loaded for the first time, it displays some default values taken from php variables. The works fine but the problem is with tag.
我有一个更新用户信息的 php 脚本。我创建了一个 html 表单,它允许用户编辑值并输入新值。现在,当第一次加载表单时,它会显示一些取自 php 变量的默认值。工作正常,但问题出在标签上。
<input type = "text" name = "name" class = "text" value = "<?php echo $user->name; ?>" />
this works fine..
这工作正常..
<select name = "department" value = "<?php echo $user->department; ?>">
<option>Information Technology</option>
<option>Computer Science</option>
<option>Electronics & Communication</option>
<option>Mechanical Engineering</option>
<option>Civil Engineering</option>
<option>Electrical & Electronics Engineering</option>
<option>M.Tech</option>
<option>MBA</option>
<option>MCA</option>
</select>
how can I solve this issue?
我该如何解决这个问题?
回答by Alexander Wolff
The Select tag doesn't have a value option. Use this instead:
Select 标签没有值选项。改用这个:
For example:
例如:
<select name = "department">
<option value="IT" <?php if ($user->department == "IT") echo "selected='selected'";?> >Information Technology</option>
<option value="CS" <?php if ($user->department == "CS") echo "selected='selected'";?> >Computer Science</option>
</select>
回答by user3024707
This can be solved with one single if statement.
这可以通过一个 if 语句来解决。
For example:
例如:
<select name = "department">
<option value="IT">Information Technology</option>
<option value="CS">Computer Science</option>
<?php if (strlen($user->department)>1 )
echo "<option value="."$user->department"."selected='selected >"."$user->department"."</option>";?>
</select>
回答by PiTheNumber
Something like this would work
像这样的东西会起作用
<select name = "department" value = "<?php echo $user->department; ?>">
<option value="1"
<?= ( $user->department == 1 ? 'selected="selected"' : '' ) ?>>
Information Technology
</option>
...
</select>