Miomir Dancevic
Miomir Dancevic

Reputation: 6852

Change background color of element?

I have issues with javascript, sorry for this but i am not good in Javascript

I am trying, to function cnagecolor on other element, and pass color what i want, but no luck :(

This is what i have for now

<script>
function changeColor(i) {
    var col = document.getElementById("changecolor");
    col.style.backgroundColor = '+i+';
}
</script>
<select id="changecolor">
<option>Kategorija</option>
<option onclick="changeColor('rgb(51,51,51)');" style="background-color:rgb(51,51,51);"></option>
<option onclick="changeColor('rgb(0,51,255)');" style="background-color:rgb(0,51,255);"></option>
<option onclick="changeColor('rgb(204,0,153)');" style="background-color:rgb(204,0,153)"></option>
<option onclick="changeColor('rgb(255,204,153)');" style="background-color:rgb(255,204,153)"></option>
</select>

Upvotes: 2

Views: 588

Answers (4)

Pal Singh
Pal Singh

Reputation: 1974

You can do something like this..

<script>
    // Execute this function on change of the select
    function changeColor() {
    var col = document.getElementById("changecolor");
    // Get the value of selected option in select
    var values = col.options[col.selectedIndex].value;
    col.style.backgroundColor = values;
}

</script>

<select id="changecolor" onchange="changeColor();">
<option>Kategorija</option>
<option value="rgb(51,51,51)">a</option>
<option value="rgb(0,51,255)">v</option>
<option value="rgb(204,0,153)">s</option>
<option value="rgb(255,204,153)">d</option>
</select>

Upvotes: 0

Sergey
Sergey

Reputation: 113

'onclick' event (and 'onselect' too) isn't supported by the option tag. So, you can use 'onchange' instead:

function select_onChange() {
   var selectElem = document.getElementById("changecolor");
   selectElem.style.backgroundColor = selectElem.value;
}

<select id="changecolor" onchange="select_onChange()">
   <option value="rgb(51,51,51)" style="background-color:rgb(51,51,51);">Option #1</option>
   <option value="rgb(0,51,255)" style="background-color:rgb(0,51,255);">Option #2</option>
</select>

Upvotes: 0

Sridhar Pendota
Sridhar Pendota

Reputation: 54

Try this

col.style.backgroundColor = i;

Upvotes: 0

Psych Half
Psych Half

Reputation: 1411

try something like...

<script>
    function changeColor() {
        var col = document.getElementById("changecolor");
        col.style.backgroundColor = col.value;
    }
</script>

 <select onchange="changeColor()" id="changecolor">
<option >Kategorija</option>
<option value="rgb(51,51,51)" style="background-color:rgb(51,51,51);"></option>
<option value="rgb(0,51,255)" style="background-color:rgb(0,51,255);"></option>
<option value="rgb(204,0,153)" style="background-color:rgb(204,0,153)"></option>
<option value="rgb(255,204,153)" style="background-color:rgb(255,204,153)"></option>
</select>

Upvotes: 3

Related Questions