Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change class of element using javascript [duplicate]

I'm having difficulties to change class of element based on selected item in select tag. This is my code:

<table> 
    <tr>
        <select onchange="wow(this.value)">
            <option value="a">a</option>
            <option value="b">b</option>            
        </select>
    </tr>               
    <tr id="x" class="show">
        x
    </tr>
</table>

<script>
function wow(value){
    switch(value){
        case "a": document.getElementById("x").className = "show"; break;       
        case "b": document.getElementById("x").className = "hide"; break;
    }
}
</script>

<style>
.show{
    display:inline-block;
}

.hide{
    display:none;
}
</style>

I don't see any problem here. I also tried setAttribute("class", "show") but doesn't work.

like image 828
shankshera Avatar asked Apr 11 '26 09:04

shankshera


1 Answers

You have to wrap X in a <td>:

http://jsfiddle.net/DerekL/CVxP7/

<tr>...<td id="x" class="show">x</td></tr>

Also you have to add case in front of "a":

case "a":
    document.getElementById("x").setAttribute("class", "show");
    break;

PS: There is a more efficient way to achieve what you are trying to do here:

http://jsfiddle.net/DerekL/CVxP7/2/

function wow(value) {
    var index = {
        a: "show",
        b: "hide"
    };
    document.getElementById("x").setAttribute("class", index[value]);
}

Now you don't need to type document.getElementById("x").setAttribute("class"... twice.

like image 129
Derek 朕會功夫 Avatar answered Apr 12 '26 23:04

Derek 朕會功夫