如何使用PHP设置HTML选择框的选定值

15

我有一个模板的下一部分:

<select name="interest">
    <option value="seo">SEO и Блоговодство</option>
    <option value="auto">Авто</option>
    <option value="business">Бизнес</option>
    <option value="design">Дизайн</option>
    ...

如何使用PHP将option元素标记为已选中?

谢谢!

10个回答

35

The manual way.....

<select name="interest">
    <option value="seo"<?php if($result['interest'] == 'seo'): ?> selected="selected"<?php endif; ?>>SEO и Блоговодство</option>
    .....

更好的方法是通过循环遍历兴趣爱好。
$interests = array(
    'seo' => 'SEO и Блоговодство',
    'auto' => 'Авто',
    ....
);

<select name="interest">
<?php foreach( $interests as $var => $interest ): ?>
<option value="<?php echo $var ?>"<?php if( $var == $result['interest'] ): ?> selected="selected"<?php endif; ?>><?php echo $interest ?></option>
<?php endforeach; ?>
</select>

1
不要忘记转义你的HTML!htmlspecialchars($var)是你的好朋友。https://dev59.com/IG025IYBdhLWcg3wCxVN - edhurtig

10
<?php
$interests = array('seo' => 'SEO и Блоговодство',  'auto' => 'Aвто', 'business' => 'Бизнес', ...);
?>
<select name="interest">
<?php
foreach($interests as $k => $v) {
?>
   <option value="<?php echo $k; ?>" <?php if($k == $result['interest']) ?> selected="selected" <?php } ?>><?php echo $v;?></option>
<?php
}
?>
</select>

5
<?php
$list='<select name="interest">
    <option value="seo">SEO и Блоговодство</option>
    <option value="auto">Авто</option>
    <option value="business">Бизнес</option>
    <option value="design">Дизайн</option>
    ...';
echo str_replace('value="' . $result['interest'] . '"','value="' . $result['interest'] . '" selected',$list);

这涉及创建一个包含您的列表的字符串,然后使用字符串替换函数查找正确的选项并将selected添加到标签中。如果使用XHTML,则需要使用selected="selected"。 这里是示例代码。

4
<select name="interest">
    <option value="seo"<?php if($result['interest'] == 'seo'){ echo ' selected="selected"'; } ?>>SEO</option>
    <option value="auto"<?php if($result['interest'] == 'auto'){ echo ' selected="selected"'; } ?>>Auto</option>
    <option value="business"<?php if($result['interest'] == 'business'){ echo ' selected="selected"'; } ?>>Business</option>
    <option value="design"<?php if($result['interest'] == 'design'){ echo ' selected="selected"'; } ?>>Design</option>
</select>

2
您需要让PHP为适当的

这似乎是一个不错的第一步回答,但我编辑了你的回答,以提供更改的解释。阅读这个可能会有所帮助。 - Alastair Brown
当你回答问题时,不要只发布答案。请提供有关您解决方案的更多信息。 - tarzanbappa
感谢 @AlastairBrown。抱歉,这是我第一次在这里发布答案。下次我会记住这件事的。 - Taha Farooqui

2
<select name="interest">
<option value="seo" <?php echo $result['interest'] == 'seo' ? 'selected' : ''?> >SEO и Блоговодство</option>
<option value="auto" <?php echo $result['interest'] == 'auto' ? 'selected' : ''?>>Авто</option>
<option value="business" <?php echo $result['interest'] == 'business' ? 'selected' : ''?>>Бизнес</option>
<option value="design" <?php echo $result['interest'] == 'design' ? 'selected' : ''?>>Дизайн</option>

1
保持你的脚本DRY和简洁,通过设置一个数组来包含你的选项数据。循环遍历数组,在模板字符串中使用占位符打印数据,以避免丑陋、笨拙的插值、连接和内联条件。
代码:(演示)
$interests = [
    'seo' => 'SEO и Блоговодство',
    'auto' => 'Aвто',
    'business' => 'Бизнес',
    'design' => 'Дизайн',
];
$selected = 'business';

echo '<select name="interest">';
foreach ($interests as $value => $text) {
    printf(
        '<option value="%s"%s>%s</option>',
        $value,
        $selected === $value ? ' selected' : '',
        $text
    );
}
echo '</select>';

对于那些付出额外努力以生成具有适当缩进的分隔选项的人,PHP 中有几种添加制表符和换行符的方法,但我不会在这里演示。

1
另一种使用可重用性的方法(如WordPress中所用)链接到WordPress代码是:
    <select name='result[interest]' style="width:400px">
        <option value='SEO' <?php selected($result['interest'], 'SEO'); ?>>SEO</option>
        <option value='AUTO' <?php selected($result['interest'], 'AUTO'); ?>>Auto</option>
    </select>

选定函数(selected())用于确定值是否被选择并设置所选选项。
/**
 * Outputs the html selected attribute.
 *
 * Compares the first two arguments and if identical marks as selected
 *
 * @since 1.0.0
 *
 * @param mixed $selected One of the values to compare
 * @param mixed $current  (true) The other value to compare if not just true
 * @param bool  $echo     Whether to echo or just return the string
 * @return string html attribute or empty string
 */
function selected( $selected, $current = true, $echo = true ) {
    return __checked_selected_helper( $selected, $current, $echo, 'selected' );
}

selected()函数接下来调用下面的辅助函数来比较并确定该值是否被选中。它返回'selected=selected'或''。

/**
 * Private helper function for checked, selected, disabled and readonly.
 *
 * Compares the first two arguments and if identical marks as $type
 *
 * @since 2.8.0
 * @access private
 *
 * @param mixed  $helper  One of the values to compare
 * @param mixed  $current (true) The other value to compare if not just true
 * @param bool   $echo    Whether to echo or just return the string
 * @param string $type    The type of checked|selected|disabled|readonly we are doing
 * @return string html attribute or empty string
 */
function __checked_selected_helper( $helper, $current, $echo, $type ) {
    if ( (string) $helper === (string) $current ) {
        $result = " $type='$type'";
    } else {
        $result = '';
    }

    if ( $echo ) {
        echo $result;
    }

    return $result;
}

0

不需要写任何东西。 只需输入以下代码

            `<div class="form-group">
                <label for="title">Blog Trending Or Not ?</label><br>
                <select class="custom-select" id="inputGroupSelect01"  name="interest">
                    
                    <option value="seo"<?php if($row['is_trending']=="seo"){echo "selected";} ?>>SEO и Блоговодство</option>
                    <option value="auto"<?php if($row['is_trending']=="auto"){echo "selected";} ?>>Авто</option>
                    <option value="business"<?php if($row['is_trending']=="business"){echo "selected";} ?>>Бизнес</option>
                    <option value="design"<?php if($row['is_trending']=="design"){echo "selected";} ?>>Дизайн</option>
                </select>
            </div>`

0

简单的缩写方法是

//after pulling your content from database
$value = interest['value'];
<option value="seo" <?php echo ($value == "seo") ? 'selected = "selected"' : '' ;?> >SEO и Блоговодство</option>
...

我希望这可以帮助到你。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接