PHP - PRE-select drop down option

前端 未结 3 416
渐次进展
渐次进展 2020-12-19 10:59

Using the example at the following URL: http://www.kavoir.com/2009/02/php-drop-down-list.html

How can I have that drop down menu pre-select one of the options such a

相关标签:
3条回答
  • 2020-12-19 11:34

    When you echo your option, echo it as follows:

    <option value="apple" selected="selected">Apple</option>
    

    Or you can use js as follows:

    var dropDownList = document.getElementById('dropDownListId');
    dropDownList.options[optionIndex].selected = true;
    

    I tweaked this function a bit but you can use it:

    function generateSelect($name, $options, $optionToSelect) {
        $html = '<select name="'.$name.'">';
        foreach ($options as $option => $value) {
            if($value == $optionToSelect)
                $html .= '<option value="'.$value.'" selected="selected">'.$value.'</option>';
            else
                $html .= '<option value="'.$value.'">'.$value.'</option>';
        }
        $html .= '</select>';
        return $html;
    }
    
    0 讨论(0)
  • 2020-12-19 11:36

    I would throw another parameter into the generateSelect function that defines what the default is. You can do this with either the id of the option or by the name. For the following, I'll use name to make it clearer.

    function generateSelect($name = '', $options = array(), $default = '') {
        $html = '<select name="'.$name.'">';
        foreach ($options as $option => $value) {
            if ($option == $default) {
                $html .= '<option value='.$value.' selected="selected">'.$option.'</option>';
            } else {
                $html .= '<option value='.$value.'>'.$option.'</option>';
            }
        }
    
        $html .= '</select>';
        return $html;
    }
    
    /* And then call it like */
    $html = generateSelect('company', $companies, 'Apple');
    
    0 讨论(0)
  • 2020-12-19 11:44
    <?php
     $selected_fruit= 2;
    
     $opt_txt=function($opt_val){           
         $selected=($selected_fruit==$opt_val)?"selected=selected":"";
         $opt_txt= "value= \"".$opt_val."\" ".$selected;
         echo $opt_txt;
         }
    ?>
    
    <select name="{$product[1]}">
      <option <?php $opt_txt(0) ?> ></option>
      <option <?php $opt_txt(2) ?> >apple</option>
      <option <?php $opt_txt(3) ?> >banana</option>
      <option <?php $opt_txt(4) ?> >pear</option>
      <option <?php $opt_txt(5) ?> >peach</option>
      <option <?php $opt_txt(6) ?> >apricot</option>
    </select>
    
    0 讨论(0)
提交回复
热议问题