How can I display content only when selecting an input type=radio

Asked

Viewed 45 times

-3

I am doing a project and I would like to know how I can make the "content a" appear only when the input "A" and the same way with the B, using jquery

 <input class="opcaoa" type="radio" name="opcao" value="A" checked="checked"> A
   <input class="opcaob" type="radio" name="opcao" value="B" > B

   <div class="text_a"><p>conteudo a</p></div>
   <div class="text_b"><p>conteudo b</p></div>

  • 2

    There it is.... I learned a new word.

  • 1

    @Augustovasques rachei! rsrsrs

1 answer

2


No need to use different classes for a collection of similar elements. To simplify, just put class in Ivds, and the same class in both:

<div class="text"><p>conteudo a</p></div>
<div class="text"><p>conteudo b</p></div>

You can select the radios by name, since they are the same:

$("[name='opcao']")

Since the first radio is already checked, you should only hide the second one in CSS:

.text:not(:nth-of-type(1)){
   display: none;
}

The selector :not(:nth-of-type(1)) excludes the first element of the class from the rule .text.

Then with jQuery you get the radio index changed with .index() and shows the div with the class .text which has the same radio index that called the event change.

I didn’t put a snippet here because it bug .index(). Test on this Jsfiddle.

CSS:

/* esconde apenas o primeiro elemento da classe */
.text:not(:nth-of-type(1)){
   display: none;
}

HTML:

<input type="radio" name="opcao" value="A" checked="checked"> A
<input type="radio" name="opcao" value="B" > B

<div class="text"><p>conteudo a</p></div>
<div class="text"><p>conteudo b</p></div>

jQuery:

$(function(){

   $("[name='opcao']").on("change", function(){
      $(".text").hide(); // esconde tudo
      var idx = $(this).index(); // pega o índice do radio
      $(".text:eq("+idx+")").show(); // mostra a classe .text pelo índice
   });

});

Browser other questions tagged

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