我尝试仅在发生错误时选择下拉列表,这是我的脚本
<select name="usertype" id="usertype" class="form-control">
<option value="">Please choose the user right</option>
<option value="admin"<?php if(isset($error)
&& $_POST['usertype'] == 'admin' ? ' selected="selected"' : '');?>>
Admin
</option>
<option value="author"<?php if(isset($error)
&& $_POST['usertype'] == 'author' ? ' selected="selected"' : '');?>>
Author
</option>
<option value="public"<?php if(isset($error)
&& $_POST['usertype'] == 'public' ? ' selected="selected"' : '');?>>
Public
</option>
</select>
谁能告诉我正确的方法?因为它不起作用。
答案 0 :(得分:1)
你正在混淆你的三元,(condition) ? true : false
。这是一个修改过的:
<?php $usertype = array('admin', 'author', 'public'); ?>
<select name="usertype" id="usertype" class="form-control">
<option disabled selected>Please choose the user right</option>
<?php foreach($usertype as $val): ?>
<option
value="<?php echo $val; ?>"
<?php echo (isset($error, $_POST['usertype']) && $_POST['usertype'] == $val) ? 'selected="selected"' : ''; ?>
>
<?php echo ucfirst($val); ?>
</option>
<?php endforeach; ?>
</select>
答案 1 :(得分:0)
试用这段代码:
<select name="usertype" id="usertype" class="form-control">
<option value="">Please choose the user right</option>
<option value="admin" <?php echo ((isset($error) && $_POST['usertype'] == 'admin') ? ' selected="selected"' : '');?>>Admin</option>
<option value="author" <?php echo ((isset($error)&& $_POST['usertype'] == 'author') ? ' selected="selected"' : '');?>>Author</option>
<option value="public" <?php echo ((isset($error) && $_POST['usertype'] == 'public') ? ' selected="selected"' : '');?>>Public</option>
</select>