Change background color of a div

0

I am trying to change the background color of a div from javascript through a select in which the client already has the colors defined for each report.

function myFunction() {
    document.getElementById("boxColor").style.backgroundColor = "lightblue";
}
#boxColor {
	width: 300px;
	height: 300px;
}
<button onclick="myFunction()">Cambiar color</button>
<br>
<br>
<select id="paleta">
    <option value="FFFFFF">FFFFFF</option>
    <option value="6F8F00">6F8F00</option>
    <option value="53AB00">53AB00</option>
    <option value="37C700">37C700</option>
    <option value="1BE300">1BE300</option>
    <option value="00FF00" selected="selected">00FF00</option>
    <option value="00DF1F">00DF1F</option>
    <option value="00C33B">00C33B</option>
    <option value="00A757">00A757</option>
</select>
<!--p><img id="myDIV" src="banio.png" alt="banio" width="580"></p-->
<p>
<div id="boxColor">
  <h1>Informe 1</h1>
  Estadisticas de ventas Eneno
</div>
</p>

So everything works fine, but I do not know how to take the colors of the select and remove the button that only change a color. Thanks

    
asked by Stn 25.10.2018 в 05:58
source

1 answer

1

The easiest thing, without modifying your code much, is to add the onchange attribute to the select tag:

<select id="paleta" onchange="myFunction(this.value)">

This way every time you select a color, the myFunction function will be triggered by sending the selected color by parameter.

Next, you modify your javascript function to receive the color parameter and apply it to the #boxColor element.

At the end your code would look like this:

function myFunction(color) {
    document.getElementById("boxColor").style.backgroundColor = "#" + color;
}
#boxColor {
	width: 300px;
	height: 300px;
}
<button onclick="myFunction()">Cambiar color</button>
<br>
<br>
<select id="paleta" onchange="myFunction(this.value)">
    <option value="FFFFFF">FFFFFF</option>
    <option value="6F8F00">6F8F00</option>
    <option value="53AB00">53AB00</option>
    <option value="37C700">37C700</option>
    <option value="1BE300">1BE300</option>
    <option value="00FF00" selected="selected">00FF00</option>
    <option value="00DF1F">00DF1F</option>
    <option value="00C33B">00C33B</option>
    <option value="00A757">00A757</option>
</select>
<!--p><img id="myDIV" src="banio.png" alt="banio" width="580"></p-->
<p>
<div id="boxColor">
  <h1>Informe 1</h1>
  Estadisticas de ventas Eneno
</div>
</p>
    
answered by 25.10.2018 / 06:26
source