0

I'm trying to show or hide some divs based on different input of user.

My problem is that, when user show a div and after hide it, that div remain as a 'white' space in height. I'd like to hide also this space, when div is hidden.

Where is my error?

I use '.removeAttribute' and '.style.visibility' to show and hide divs. I tried also with '.hide' but in this case divs not go in hide.

Here my code:


function changeThis1(sender) { 
  if(document.getElementById('data1').checked){
    document.getElementById("div1").removeAttribute('style'); 
    document.getElementById("div2").style.visibility = "hidden"; 
  }
  else{
    document.getElementById("data1").disabled = true;   
  } 
}

function changeThis2(sender) { 
  if(document.getElementById('data2').checked){
    document.getElementById("div2").removeAttribute('style'); 
    document.getElementById("div1").style.visibility = "hidden"; 
  }
  else{
    document.getElementById("data2").disabled = true;   
  } 
}

<div>   
    <input type="radio" id="data1" name="data" onchange="changeThis1(this)">
        <div class="kw_scelta"><strong>First</strong>
        </div>  
            <div id="div1" style="display: none;">
                    Data 1 <input id="datas1" type="number" /><br>
                </div>
</div>

<div>   
    <input type="radio" id="data2" name="data" onchange="changeThis2(this)">
        <div class="kw_scelta"><strong>Second</strong>
        </div>  
            <div id="div2" style="display: none;">
                    Data 2 <input id="datas2" type="number" /><br>
                </div>
</div>
James
  • 53
  • 7
  • 2
    `display: none`? from [mdn](https://developer.mozilla.org/en-US/docs/Web/CSS/display): "_Turns off the display of an element so that it has no effect on layout (the document is rendered as though the element did not exist). All descendant elements also have their display turned off. To have an element take up the space that it would normally take, but without actually rendering anything, use the visibility property instead._" – Diego D Aug 24 '22 at 09:20
  • since you have them on `display: none` why not just do `.style.display = "block"`?? and if they are not checked, go back to `display: none` – RandomCoder Aug 24 '22 at 09:22
  • https://developer.mozilla.org/en-US/docs/Web/CSS/visibility: _"The visibility CSS property shows or hides an element without changing the layout of a document. [...] To both hide an element and remove it from the document layout, set the display property to none instead of using visibility."_ – CBroe Aug 24 '22 at 09:23

1 Answers1

1

To achieve this you should use

display: none;

instead of visibility: hidden

this
  • 94
  • 1
  • 6