Hide element with Javascript. Doesn't work with IE and Chrome

Timo picture Timo · Jul 20, 2011 · Viewed 11k times · Source

I have problems with hiding elements. I already read this topic Javascript working on Firefox but not in Chrome and IE6 but didn't get help from there. Javascript code, what should hide/show textbox and radio buttons:

function hide1(a)
{
var text1=document.getElementById("text1");
text1.style.visibility = 'visible';
text1.value = a;

document.getElementById("radio1").style.visibility = 'hidden';
document.getElementById("radio2").style.visibility = 'hidden';
document.getElementById("rlabel").style.visibility = 'hidden';
}

function show1()
{
document.getElementById("text1").style.visibility = 'hidden';
document.getElementById("radio1").style.visibility = 'visible';
document.getElementById("radio2").style.visibility = 'visible';
document.getElementById("rlabel").style.visibility = 'visible';
}

And HTML:

<select id='listb2'>
  <option onclick='hide1("$age");' value='1'>Age</option>
  <option onclick='show1();' value='2'>Sex</option>
</select>

Now with Firefox and Opera it change radio buttons and textbox to visible/hidden when I choose one of the options. But with Chrome and IE they wouldn't. I also tried with "... .style.display = 'none';" nothing happened (on IE and Chrome, FF and Opera it works) even this time.

FF 5.0; Chrome 12; IE 8; Opera 11.50

Now works with:

<select onchange='hideshow(this.value);' id='listb2'>
  <option value='1'>Age</option>
  <option value='2'>Sex</option>
</select>

Answer

Town picture Town · Jul 20, 2011

onclick isn't valid for option elements.

Handle the onchange event of the select instead, get the selected value using the code below and then do your conditional processing.

var element = document.getElementById("listb2");
var selectedValue = element.options[element.selectedIndex].value;