Danahlen Danahlen - 1 year ago 51
Javascript Question

Javascript changing the visibility of a div depending on what option in <select> not working

I'm trying to create a function where the user picks an option from a drop-down box, and the site should show a hidden div depending on which option the user picks.

The Dropdown box:

<select id="pick">
<option value="v2">2</option>
<option value="v3">3</option>


<input type="button" value="Generate" onclick="genFunc(this)" />


function genFunc(sel) {
var value = sel.value;
var divChange = value;
var divChange = "document.getElementById("+ sel.value +")";

divChange.style.visibility= "visible" ;



#v2 {
visibility: hidden;

#v3 {
visibility: hidden;


<div id="v2">test1</div>
<div id="v3">test2</div>

When I press the button I get this error instead:

Uncaught TypeError: Cannot set property 'visibility' of undefined

I can't find out why I'm getting this error.
Also, I'm sorry if all of this is written clumpsy.

Answer Source

There are two problems

  1. this value you are passing in onclick is button, not select
  2. You are using string, to get divChange, instead of an actual function

Try this:

function genFunc() {
    var sel = document.getElementById("pick");
    var divChange = document.getElementById(sel.value);
    divChange.style.visibility= "visible" ;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download