Select shows blank Background of your selected options

1

I have a Select which contains 3 colors as options, but when I select an option it does not show the background color, it only shows the text:

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
        <title>Puntos...</title>
        <style type="text/css">
            .rojo {background-color:#FF0000;}
            .azul {background-color:#0066FF;}
            .verde {background-color:#009900;}
        </style>
    </head>

    <body>
        <form action="" method="">
            <select name="opciones">
                <option class="rojo">Rojo</option>
                <option class="azul">azul</option>
                <option class="verde">Verde</option>
            </select>
        </form>
    </body>
</html>
    
asked by Ivxn 15.03.2018 в 16:53
source

2 answers

6

for this it is necessary to use javascript and handle the event onchange to change the background of the select depending on the selected option

add the following code after the closing tag </style>

<script>
    var e = document.getElementsByName("opciones")[0];

    e.className = e.options[e.selectedIndex].className;

    e.onchange = function(){
      e.className = e.options[e.selectedIndex].className;
    }
</script>

watch the code working

Edit

If you want to use atributo style instead of classes css you should access each css property in the style and modify its value

    var e = document.getElementsByName("opciones")[0];

    e.style.backgroundColor = e.options[e.selectedIndex].style.backgroundColor;

    e.onchange = function(){
      e.style.backgroundColor = e.options[e.selectedIndex].style.backgroundColor;
    }

look at the code working for this update

    
answered by 15.03.2018 в 17:10
2

I would do it with JQuery in this way. I hope it serves you.

var select = $("select"); // Select
// Estado inicial del Select. Agregar clase de la opción seleccionada.
select.attr("class", select.children(":selected").attr("class"));

// Al cambiar
select.change(function() {
   var selected = $(this).children(":selected").attr("class");
   $(this).attr("class", selected);
});
.rojo {
  background-color: #FF0000;
}

.azul {
  background-color: #0066FF;
}

.verde {
  background-color: #009900;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="opciones" id="myselect">
    <option class="rojo">Rojo</option>
    <option class="azul">azul</option>
    <option class="verde">Verde</option>
</select>
    
answered by 15.03.2018 в 21:04