steeve
steeve

Reputation: 699

Javascript for showing and hiding a div based on select options

I need some JavaScript code to validate the page. Here is the html,

<select id="sel">
<option value="0" selected="selected">Please select</option>
<option value="first">Link 1</option>
<option value="second">Link 2</option>
<option value="third">Link 3</option>
<option value="last">No Link</option>
</select>

<div class="sample" style="display:none;">Sample Text</div>
<input type="button" value="submit" class="inputclass" />

Need some JavaScript code,

  1. when user clicks first or last option, show the div and hide the button
  2. when user clicks any of the link, hide the div and show the button

P.S :

Options in the Select will generate dynamically from the database. My page will only run in JavaScript, hence no need of Jquery.

Please help...

Upvotes: 1

Views: 743

Answers (1)

Endre Simo
Endre Simo

Reputation: 11551

I think this is the code what you need:

The JS part:

function getSelection(e) {   
    var selection = document.getElementsByTagName("option");
    var index=document.getElementById("sel").selectedIndex;
    var text = document.getElementById("sample");
    var button = document.getElementById("input");
    var option=document.getElementById("sel").options;

    if (option[index].value == "first" || option[index].value == "last") {
        text.style.display = "block";
        button.style.display = "none";
    } else {
        if (text.style.display != "none") {
            text.style.display = "block";
            button.style.display = "none";
        }
        else {
            text.style.display = "none";
            button.style.display = "block";
        }        
    }

    return false;    

}



document.getElementById("input").onclick = function() { getSelection() };

And the HTML (i slightly modified the original one to have access more efficiently to html elements):

<select id="sel">
<option value="0" selected="selected">Please select</option>
<option value="first">Link 1</option>
<option value="second">Link 2</option>
<option value="third">Link 3</option>
<option value="last">No Link</option>
</select>

<div id="sample" style="display:none;">Sample Text</div>
<input type="button" value="submit" id="input"/>​

...and the Fiddle : http://jsfiddle.net/eaRwa/2/

Upvotes: 2

Related Questions