只有在提交时出现错误时才会选择粘性下拉列表

时间:2014-12-20 02:03:42

标签: php html post sticky

我尝试仅在发生错误时选择下拉列表,这是我的脚本

<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>

谁能告诉我正确的方法?因为它不起作用。

2 个答案:

答案 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>