简体   繁体   中英

Display next div only if user select radio button on current div


I need to display to user the next div only if he select a radio button from the current div...Let me explain:

<h1>First question</h1>
<input type="radio" id="2" value="Dog">Dog<br>
<input type="radio" id="2" value="Cat">Cat<br>
<br>
<div id='2div'><h1>Second question</h1>
<input type="radio" id="3" value="Blue">Blue<br>
<input type="radio" id="3" value="Green">Green<br>
</div>

(I have something like 39 div)

I need to display div2 only if user select one of the two radio button that is present on div1.

I tried with:

$(document).ready(function () {

$('div').hide();

$("input[type=radio]").change(function() {

     $( '#' + $(this).attr('id') + 'div' ).show();

    $('div:not(#' + $(this).attr('id') + 'tab)' ).hide();

});

});

But Is not working...

How can I do this? Thanks

The main issue seems to be that the <div> is shown and then immediately hidden again.

For example, #2div is shown.
But it is also not #2tab , so it is hidden.

Also note that IDs must be unique in HTML.
Consider using a data attribute instead.
See jQuery's data() .

 $(function() { $("input[type=radio]").change(function() { var id = $(this).data('id'); $('#' + id + 'div').show(); //$('div:not(#' + id + 'tab)').hide(); }); }); 
 div { display: none; } 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <h1>First question</h1> <input type="radio" name="animal" data-id="2" value="Dog">Dog<br> <input type="radio" name="animal" data-id="2" value="Cat">Cat<br> <br> <div id="2div"> <h1>Second question</h1> <input type="radio" name="color" data-id="3" value="Blue">Blue<br> <input type="radio" name="color" data-id="3" value="Green">Green<br> </div> <div id="3div"> <h1>Third question</h1> <input type="radio" name="shape" data-id="4" value="Blue">Round<br> <input type="radio" name="shape" data-id="4" value="Green">Square<br> </div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM