Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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>
like image 270
Timo Avatar asked Jul 20 '11 12:07

Timo


3 Answers

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;
like image 144
Town Avatar answered Oct 27 '22 14:10

Town


Instead of setting 'visibility' to 'hidden', try setting 'display' to 'none'.

document.getElementById('header').style.display = 'none';

EDIT: Not quite sure whether you can set the onclick property on an option element in those browsers... Try using onchange on your surrounding select tag instead.

like image 41
Pelle Avatar answered Oct 27 '22 14:10

Pelle


I realy encourage you to use jQuery for that. jQuery guarantees that this will work in every browser. In query its very easy

<script>
    $().ready(function () {
        $("#listb2").change(function () {
            if ($("#listb2").val() == "1")
                $("#radio1, #radio2, #rlabel").show();
            else
                $("#text1, #radio1, #radio2, #rlabel").hide();
        });
    });
</script>

<select id='listb2'>
  <option value='1'>Age</option>
  <option value='2'>Sex</option>
</select>
like image 39
dknaack Avatar answered Oct 27 '22 13:10

dknaack