I have a php generated select option menu on my page with the options ‘Unverifed’, ‘Verified’ and ‘Banned’.
I am attempting to (automatically) change the background color of the statusField, based on which option is pre-selected (from database).
Corresponding Status options and background colors should be as follows:
Unverified – orange
Verified – green
Banned – red
For testing purposes, I am able to achieve the background color change (manually), by using ‘Select Option Menu Example #1’ (below), along with the ‘Change Background Color’ script below.
However… I will not be using Example #1 field on my site.
I will be using the php version, ‘Example #2’, so that I can populate the statusField’s pre-selected option with the particular status stored in the database.
Unfortunately… when I attempt to use the same ‘Change Background Color’ script with Example #2, the color does not automatically change.
Select Option Menu Example #1
<select id="status" name="status" class="statusField" value="<?php echo $_POST['status']; ?>">
<option value="Unverified" class="unverified">Unverified</option>
<option value="Verified" class="verified">Verified</option>
<option value="Banned" class="banned">Banned</option>
</select>
Select Option Menu Example #2
<?php
$selected = "$status";
$options = array('Unverified', 'Verified', 'Banned');
echo "<select id='status' name='status' class='statusField'>";
foreach($options as $option){
if($selected == $option) {
echo "<option selected='selected' value='$option'>$option</option>";
}
else {
echo "<option value='$option'>$option</option>";
}
}
echo "</select>";
?>
Change Background Color – Script
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$(document).on("change", ".statusField", function(){
var colors = ["orange", "green", "red"];
var wth = $(this).find(":selected").index();
var color = colors[ wth ];
$(".statusField").css("background-color", color );
});
});
</script>