简体   繁体   中英

How to do a pre-select drop down in PHP with added description?

I liked the function contributed here: PHP - PRE-select drop down option

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

/* And then call it like */
$html = generateSelect('company', $companies, 'Apple');

However, this doesn't address a description that is needed sometimes with drop-down menu.

For example:

<select name="ranges">
<option value="0">All Ranges</option>
<option value="1">Under $10,000</option>
<option value="2">$10,000 - $25,000</option>
<option value="3">$25,000 - $50,000</option>
<option value="4">$50,000 - $75,000</option>
<option value="5">$75,000 - $100,000</option>
<option value="6">$100,000 - $200,000</option>
<option value="7">$200,000 or more</option>
</select>

What needs to be modified for the generateSelect function to allow it to assign, for example, along with a value of "4", but a description of "$75,000 - $100,000" to accompany it? The way the generateSelect function is now, it would assign a value of "4" and place in the description (for lack of a better term) also a "4".

Or is there a better way to do this in PHP? Thanks!

I am not sure what you mean by description (perhaps you could clarify; do you want an additional attribute that contains the option key? I am unregistered so I cannot ask except as an answer)

If you want for example to show the "description" as part of the value attribute, you would simply append it to the value attribute like so:

$html .= '<option value="'.$value.' ('.$option.')" selected="selected">'.$option.'</option>';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM