keelerjr12 keelerjr12 - 5 months ago 23
PHP Question

Color background <Select> on page load

I have 100+ select/option boxes that I populate based on table data. I have the options colored based on which option is selected (i.e. 'Available' is blue, 'Unavailable' is red).

However, when the page loads, the SELECT box stays white. On the color change I use:

<script>
function setBg(sel) {
sel.style.backgroundColor = sel.options[sel.selectedIndex].style.backgroundColor;
}
</script>

function display_day($day, $current_status, $list_of_statuses)
{
echo "<select name=" . $day ."[] onChange=\"setBg(this)\">";
if (!$current_status)
{
echo "<option disabled selected value> -- select an option -- </option>";
}

foreach ($list_of_statuses as $key => $row)
{
echo "<option value='" . $row['status'] . "'";
echo " style = \"color: " . $row['fg_color'] . "; background-color: " . $row['bg_color'] . "\"";

if ($row['status'] == $current_status)
{
echo " selected=\"selected\"";
}

echo ">" . $row['status'] . "</option>";
}

echo "</select>";
}


This obviously only changes color when the SELECT changes. I tried to use onload, but this didn't work. Any ideas how to get the SELECT to color on load when data is pulled from MySQL database.

Answer Source

You don't need onload, you can simply do it like you did for the options, just add style="background-color".

Instead of echoing the HTML code, save it in a string variable, and echo the variable after the loop. First save the loop to the variable and use a separate variable to save the active color when $row['status'] == $current_status. Then after the loop, add the <select ... with the color from the color variable, and then add closing </select>, then echo the result.

Here is a quick code (untested, so you may have to modify):

$select = "";
$color = "";

if (!$current_status)
{
    $select = "<option disabled selected value> -- select an option -- </option>";   
}

foreach ($list_of_statuses as $key => $row)
{
    $select = $select . "<option value='" . $row['status'] . "'";
    $select = $select . " style=\"color: " . $row['fg_color'] . "; background-color: " . $row['bg_color'] . "\"";

    if ($row['status'] == $current_status)
    {
        $select = $select . " selected=\"selected\"";
        $color = $row['bg_color'];
    }

    $select = $select . ">" . $row['status'] . "</option>";
}

$select = "<select name=" . $day ."[] onChange=\"setBg(this)\" style=\"background-color: " . $color . "\">" . $select + "</select>";

echo $select;