Is having multiple pre-selected values in <select multiple> possible?

Is it possible to have multiple pre-selected options in a box? Below is my PHP code which makes logical sense to me and appears to output the correct HTML with everything in the right place, but it doesn’t actually display with any options selected on the page.

<?php

$options = $wpdb->get_results( $query); 
$number = count($options);

$optionsChosen = explode(",", $userInfo->userOptions); 
// This is the list of options the user has chosen, separated by commas, i.e. "service1, service2,"

echo "<select name="option[]" id="option" size="$number" multiple>n";

foreach ( $options as $thisOption ) { 
    echo "<option value="$thisOption->optionName" title="";
    echo stripslashes($thisOption->optionDescription)."" ";

    for($i=0; $i<count($optionsChosen); $i++){
        if($optionsChosen[$i]==$thisOption->optionName){
            echo "selected="selected" ";
        } // End if()
    } // end for()

    echo ">$thisOption->optionName</option>n";
 } // end foreach()
 ?>
 </select>

This is my PHP, and the HTML it’s outputting looks fine and includes the selected=”selected” in the right place for the appropriate values, but for whatever reason they aren’t actually selected. Is this just not a possible thing in HTML? This works fine for me if I only have one possible selection, but I can’t seem to find anywhere online mentioning that its only supported for single tags. If this isn’t possible, is there a way to achieve something similar?

Read More

Edit: As everybody says, it works fine. For whatever reason, refreshing the page (which was built using get variables) in Firefox would refresh the source code but not what was shown inside the browser, closing the page and re-opening it made it work as predicted.

Related posts

Leave a Reply

2 comments

  1. Yes, a <select> tag with multiple attribute can have multiple options with selected="selected" attrubute, which will automatically make these options selected on page load.

  2. Yes Element in HTML can have multiple options selected. If it has multiple attribute.

    Below is code

    <select multiple>
                <option>India</option>
                <option selected>USA</option>
                <option>Canada</option>
                <option selected>China</option>
    </select>