Wednesday, November 08, 2006

Show and hide a div based on a dropdown list

I've been playing with some javascript. I've seen more and more web pages that show and hide pieces based on values in the page without reloading the page, so I wanted to see what it took. I searched and had to find answers at several different sites, so I thought I'd put my research into a single place. If nothing else, I can refer back to this later.

First, I placed the Javascript code to show and hide the DIV immediately after my BODY tag.

<script type="text/javascript">


function showmessage(id, id2) {

        if(document.getElementById(id2).value == 'MAC')


function hide_div(id) {

        var e = document.getElementById(id); = 'none';


function show_div(id) {

        var e = document.getElementById(id); = 'block';




Then in my code where I want the message to go, I have a DIV tag.
<div id="sometimes" style="display:none;"><br>You really should select something else.</div>

I have the default set to hidden, because I only want it to show when a value is selected.

Finally, in order to show an hide it, there has to be a change that causes it. I have a select value determining whether or not the message is shown, but the examples I saw all showed it from an Anchor tag. Anytime a form event could fire though, the function could be called to show or hide the div.

<select ID="FavoritComputer" NAME="FavoritComputer" onChange="showmessage('sometimes', 'FavoritComputer');">

No comments: