【问题标题】:Sticky dropdown selected only if there's error on submit仅在提交时出现错误时才选择粘性下拉菜单
【发布时间】:2014-12-20 02:03:41
【问题描述】:

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

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

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

【问题讨论】:

    标签: php html post sticky


    【解决方案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>
    

    【讨论】:

    • @Kyo 很高兴这有帮助
    【解决方案2】:

    试试这个代码:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-27
      • 1970-01-01
      相关资源
      最近更新 更多