Quantcast
Channel: Active questions tagged html - Stack Overflow
Viewing all articles
Browse latest Browse all 67441

Javascript: How to show/hide between two div using radiobutton?

$
0
0

I have problems on hiding/showing an image using radio-buttons with JavaScript. What I want to do is that, when loading the page, only the first image will be shown by default while the second image is hidden. Then the user can choose which one to show or hide when clicking the radio-buttons.

Here's a snippet of what I've done so far.

<input type="radio" name="img1" onclick="img(0)" checked>Image 1
<input type="radio" name="img2" onclick="img(1)">Image 2

<div id="img1">
  <!-- insert image -->
</div>
<div id="img2">
  <!-- insert image -->
</div>


<script>
  function img(x){
    if(x==0){
      document.getElementById('img2').style.display='none';
      document.getElementById('img1').style.display='block';
    }
    else{
      document.getElementById('img1').style.display='none';
      document.getElementById('img2').style.display='block';
    }
    return;
  }
</script>

The problem in here is that, after loading the page, the two image is shown. The second image will only be hidden after clicking the radio-button for the first image and vice versa. Also, the checked attribute is not working.


Viewing all articles
Browse latest Browse all 67441

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>