You can get the style of the option selected with attr
for the style
attribute and apply it to the% with%. To get the selected you can use select
.
Example:
$("select.md-form-control").on("change", function(){
$(this).attr("style", $(this).find(":selected").attr("style"));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><selectname='Situacao[]'class='md-form-control'><optionvalue=''style=''>Selecione</option><optionvalue='Pago'style='background-color:#006400;color:#FFF'>Pago</option><optionvalue='NãoPago'style='background-color:#F00;color:#FFF'>NãoPago</option><optionvalue='Aguardando'style='background-color:#FF8C00;color:#FFF'>Aguardando</option></select>
NotethatIhadtoincludeafind(":selected")
in the style=''
option to return to the initial style.
You can also do the same with classes that get more flexible and scalable. In this case not only the application is slightly different, as the% html of Selecione
itself is also different.
Before applying a new class remove the ones you already have with <select>
, passing only the ones you want to remove. Then they get the new one to apply from the selected element with removeClass
.
Example:
$("select.md-form-control").on("change", function(){
$(this).removeClass("pago naopago aguardando"); //remover qualquer uma destas classes
$(this).addClass($(this).find(":selected").attr('class'));
});
.pago {
background-color: #006400;
color: #FFF;
}
.naopago {
background-color: #F00;
color: #FFF;
}
.aguardando {
background-color: #FF8C00;
color: #FFF;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name='Situacao[]' class='md-form-control'>
<option value='' >Selecione</option>
<option value='Pago' class='pago'>Pago</option>
<option value='Não Pago' class='naopago'>Não Pago</option>
<option value='Aguardando' class='aguardando'>Aguardando</option>
</select>