0
I have a code, which changes the CSS of the element SELECT based on the value that is currently selected. The problem is that I have over 100 Selects to apply this effect, but my code only reads the first VALUE of the first SELECT, takes the color and applies it to everyone’s CSS. But my goal is for him to read one by one and apply the CSS in Select according to the currently selected value.
Below I put a code just for example. But this is for a PHP form, which pulls the data from the database and displays on the screen. Therefore, you cannot change the CSS directly in SELECT. I need that when the form is loaded, it sees which OPTION is with the SELECT attribute, read its CSS and copy to the SELECT parent element.
Currently, I have the code below:
<div class="form-group">
<select name="label" id="aaaaa" class="checkitens">
<option style="background-color:red;"selected class="form-control checkitens optionred2">red</option>
<option style="background-color:green;" class="form-control checkitens optiongreen2">green</option>
<option style="background-color:yellow;" class="form-control checkitens optionyellow2">yellow</option>
</select>
</div>
<div class="form-group">
<select name="label" id="bbbbb" class="checkitens">
<option style="background-color:red;" class="form-control checkitens optionred2">red</option>
<option style="background-color:green;"selected class="form-control checkitens optiongreen2">green</option>
<option style="background-color:yellow;" class="form-control checkitens optionyellow2">yellow</option>
</select>
</div>
And the following JS:
$(document).ready(function(){
setColor();
$('select.label').change(function(){
setColor();
});
});
function setColor()
{
var color = $('select.checkitens').find('option:selected').attr('class');
$('select.checkitens').addClass(color);
}
And the CSS:
.optiongreen2 {color: #25d366 !important;background: #25d3660d !important}
.optionyellow2 {color: #ffc905 !important;background: #ffc9050d !important}
.optionred2 {color: red !important;background: #ff00000d !important;}
This needs to be read and applied when the page is only loaded. Because when the user changes the value of SELECT, it already loads the new value and color automatically, because in this case, add an onchange attribute, direct in HTML, thus:
<select name="chk_comvenda" id="chk_comvenda" class="form-control checkitens" onchange="this.className=this.options[this.selectedIndex].className">
<option class="form-control checkitens optionred2" value="1" @if($project->chk_comvenda == '1') selected @endif value="not started">1</option>
<option class="form-control checkitens optionred2" value="2" @if($project->chk_comvenda == '2') selected @endif value="on hold">2</option>
</select>
why the downvote?
– Alexis Garcia