How to hide div when selecting radio options

Asked

Viewed 752 times

2

As trivial as it may seem I’m having trouble executing this script, the problem I have is this, when entering a page I show a div with selected content from my database and this is being done correctly, From then on the user has the option to show this information in a Grid or in a List, I created a radio with two options, Grid and List and I am trying to hide the first div that is shown when entering the page when one of these options is selected. What I’ve done so far is this:

    $(window).load(function(){  
        $(':radio').change(function (event) {       
            var id = $(this).data('id');
            $('#' + id).addClass('none').siblings().removeClass('none');

            if ((id == "lista") || (id == "grid")) {
                document.getElementById('geral').style.display="none";                          
            }

        }); 
    });

The divs are like this:

<div id="geral">
  Geral Mostra ao entrar na página
</div>

<div id="lista" class="none">
  Lista, mostra ao selecionar Lista no radio
</div>

<div id="grid" class="none">
  Grid, mostra ao selecionar Lista no radio
</div>

1 answer

3


You can simply check the event .change() and change the display.

$(document).ready(function() {
    $('input[type=radio]').change(function() {
        if (this.value == 'geral') {
            $("#geral").css("display","block");
            $("#lista").css("display","none");
            $("#grid").css("display","none");
        }
        else if (this.value == 'lista') {
            $("#lista").css("display","block");
            $("#geral").css("display","none");
            $("#grid").css("display","none");
        }
         else if (this.value == 'grid') {
            $("#grid").css("display","block");
            $("#lista").css("display","none");
            $("#geral").css("display","none");
        }
    });
});
.none{
    display:none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="radio" name="group" value="geral">Geral<br>
<input type="radio" name="group" value="lista">Lista<br>
<input type="radio" name="group" value="grid">Grid<br/>

<div id="geral">
  Geral Mostra ao entrar na página
</div>

<div id="lista" class="none">
  Lista, mostra ao selecionar Lista no radio
</div>

<div id="grid" class="none">
  Grid, mostra ao selecionar Lista no radio
</div>

You can add or remove the class equal to your example, but it is up to you.

Example in Jsfiddle.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.