1

Hi I whant that some element in my page appears only when a check box is selected, and disappears when it is not.

So I have this HTML:

<td><input type="checkbox" onchange="test('f1')"> Is selected?</td>
<div id="f1">some content</div>

And JavaScript:

function test(id) {
  if (document.getElementById(id).style.visibility === "hidden") {
      document.getElementById(id).style.visibility = "visible";
  } else {
      document.getElementById(id).style.visibility = "hidden";
  }
}

And CSS:

#f1 {visibility: hidden;}

Right now it is working but not perfect, because the first select is always hidden.

pid
  • 11,472
  • 6
  • 34
  • 63
piotr
  • 45
  • 1
  • 7
  • possible duplicate of [How to retrieve a style's value in javascript?](http://stackoverflow.com/questions/2664045/how-to-retrieve-a-styles-value-in-javascript) and many others – JJJ Jan 25 '14 at 13:11
  • OK I understand now, that it is hard to do in that wy with css file :) can close – piotr Jan 25 '14 at 13:23

1 Answers1

0

As Juhana stated in the comments, the answer you're looking, which is explained perfectly in the link - is that: .style.* only looks at inline elements, quote:

"The element.style property lets you know only the CSS properties that were defined as inline in that element (programmatically, or defined in the style attribute of the element), you should get the computed style."

If you tweak your function a little bit to check if .style.visibility hasn't been set yet (thus ''), it'll toggle it upon first click.

function changeVisiblity() {
    if ( getContent.style.visibility == "hidden" || getContent.style.visibility == '' ) {
        getContent.style.visibility = "visible";  
    } else {
        getContent.style.visibility = "hidden";    
    }
}

Secondly, try to teach yourself to keep away from onclick within HTML elements, as this makes it much harder to maintain the future.

var getCheckbox = document.getElementById("testcheckbox"),
    getContent = document.getElementById("f1");

getCheckbox.addEventListener( 'change', changeVisiblity, null );

Demo Fiddle: http://jsfiddle.net/4yfWD/

MackieeE
  • 11,751
  • 4
  • 39
  • 56