仅当提交时出现错误时,才会选择粘滞下拉列表


Sticky dropdown selected only if there's error on submit

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

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

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

你混淆了你的三元,它的(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>

尝试以下代码:

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