Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show and hide div elements based on dropdown selection in html using javascript

I have a question using javascript to show hide a div when using a dropdown. Code works for links and buttons but im asking if there's any way to rewrite it so it can use the SELECT option. Like if i select 'Show' from dropdown it will show me the div containing 'Hello world!'

My current Javascript:

<script>
function showMe(id) {
    var e = document.getElementById(id);
    if(e.style.display == "block") {
        e.style.display = "none";
    } else {
        e.style.display = "block";
    }
}
</script>

And the index.html contains:

<select>
    <option>Hide</option>
    <option onselect="showMe('idShowMe')">Show</option>
</select>

<div id="idShowMe" style="display: none">
    <b>Hello world!</b>
</div>
like image 836
User_T Avatar asked Sep 21 '25 10:09

User_T


1 Answers

You can change your code

function showMe(e) {
    var strdisplay = e.options[e.selectedIndex].value;
    var e = document.getElementById("idShowMe");
    if(strdisplay == "Hide") {
        e.style.display = "none";
    } else {
        e.style.display = "block";
    }
}
<select onchange="showMe(this);">
    <option>Hide</option>
    <option>Show</option>
</select>

<div id="idShowMe" style="display: none">
    <b>Hello world!</b>
</div>
like image 76
Silence Peace Avatar answered Sep 23 '25 00:09

Silence Peace