简体   繁体   中英

jQuery Click Function: Show Div Based on Previous Radio Button Selection

I have been searching for an answer all day but can't seem to find anything that would help my specific problem so here goes.

In a question form, I want to show hidden divs based on radio button selections, using the jQuery click() function. But after a second click() event is triggered, the div that was shown in the previous selection is forgotten, and returned to hidden status.

Here is an example code:

 jQuery(document).ready(function(){ jQuery('input[type="radio"]').click(function(){ if(jQuery(this).attr("value")=="answer1"){ jQuery(".hide").hide(); jQuery(".answer1").show(); jQuery(".answer1and2").show(); } if(jQuery(this).attr("value")=="answer2"){ jQuery(".hide").hide(); jQuery(".answer2").show(); jQuery(".answer1and2").show(); } if(jQuery(this).attr("value")=="answer3"){ jQuery(".hide").hide(); jQuery(".answer1and2").show(); jQuery(".answer3").show(); } }); }); 
 .hide { display: none; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script> <h1>Question 1</h1> <input type="radio" name="question1" value="answer1"> Answer 1 <input type="radio" name="question1" value="answer2"> Answer 2 <div class="answer1 hide"> <p>Answer 1 is Apple</p> </div> <div class="answer2 hide"> <p>Answer 2 is Mango</p> </div> <div class="answer1and2 hide"> <h1>Question 2</h1> <input type="radio" name="question2" value="answer3"> Any answer <input type="radio" name="question2" value="answer3"> Any answer </div> <div class="answer3 hide"> <p>Did you choose Apple or Mango?</p> </div> 

How can I retain just one of the answers that was shown after the first selection?

JSFiddle code here

If you don't want shown divs to be hidden again, then just remove "hide" class from items you get "shown"

Here is JSFiddle

And here is one example row of how to do that:

         jQuery(".answer1").show().removeClass('hide');

Just remove every

jQuery(".hide").hide();

(now with fiddle )

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