You can get the style of the selected option with attr
for the attribute style
and applies it to select
. To get the selected you can use find(":selected")
.
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>
<select name='Situacao[]' class='md-form-control'>
<option value='' style=''>Selecione</option>
<option value='Pago' style='background-color: #006400; color: #FFF'>Pago</option>
<option value='Não Pago' style='background-color: #F00; color: #FFF'>Não Pago</option>
<option value='Aguardando' style='background-color: #FF8C00; color: #FFF'>Aguardando</option>
</select>
Note that I had to include a style=''
in the option Selecione
to return to the initial style.
You can also do the same with classes that are more flexible and scalable. In this case not only is the application slightly different, but the html of the <select>
also looks different.
Before applying a new class remove the ones you already have with removeClass
passing only the ones we want to remove. Then get the new one to apply from the selected element with attr('class')
.
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>
Hello Isac, yes... but when I do this, select is not the color of the option. For example: if I select Pago, I would like the select to be green, but it is still white.
– user24136
Sorry Isac. I altered my post. I really ended up not being clear in my doubt.
– user24136
As I saw php, I thought it was related to the value, only after I realized that the goal was the style.
– Isac