How to set selected value of HTML select box with PHP

后端 未结 8 816
暖寄归人
暖寄归人 2020-11-30 11:19

I have a next piece of the template:


                        
    
提交评论

  • 2020-11-30 11:48

    The manual way.....

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

    The better way would be to loop through the interests

    $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>
    
    0 讨论(0)
  • 2020-11-30 11:49
    <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>
    
    0 讨论(0)
  • 2020-11-30 11:57

    Simple short hand method would be

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

    I hope this helps

    0 讨论(0)
  • 2020-11-30 11:59
    <?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>
    
    0 讨论(0)
  • 2020-11-30 11:59

    You need to get PHP to insert the selected="selected" attribute for the appropriate <option> tag, like this:

    <?php $result=$userRow['ad_type']; ?>
               <select class="form-control" name="ad_type">
                  <option <?php if($result == 'text'){ echo ' selected="selected"'; } ?> value="text">Text</option>
                  <option <?php if($result == 'image'){ echo ' selected="selected"'; } ?> value="image">Image</option>
                  <option <?php if($result == 'video'){ echo ' selected="selected"'; } ?> value="video">Video</option>
                  <option <?php if($result == 'htmladsense'){ echo ' selected="selected"'; } ?> value="htmladsense">Html Adsense</option>
                </select>
    
    0 讨论(0)
  • 提交回复
    热议问题