Show hidden content when switch using jQuery

I have two checkboxes

ABC XYZ 

when ABC is checked, I show abc content div and when XYZ is checked, I show xyz div content

everything works fine, only when I click on the ABC and XYZ radio buttons, suppose that if the ABC radio button is selected by default, the abc content div is not displayed only when clicked, I get its contents

My requirement is that when the radio switch is checked, I have to get the hidden content of this selected switch without clicking

can someone help me achieve this

http://jsfiddle.net/Qac6J/497/

HTML

 <form id='group'> <div> <label> <input type="radio" name="group1" class="trigger" data-rel="abc" checked />ABC </label> <span class="abc content"> <label> <span>I belong to ABC</span> <input type="button" value="ABC"/> </label> </span> </div> <br> <div> <label> <input type="radio" name="group1" class="trigger" data-rel="xyz"/>XYZ </label> <span class="xyz content"> <label> <span>I belong to XYZ</span> <input type="button" value="XYZ"/> </label> </span> </div> </form> 

CSS

 .content { display: none; } 

JQuery

 $('.trigger').change(function() { $('.content').hide(); $('.' + $(this).data('rel')).show(); }); 
+5
source share
2 answers

You need to get the rel value of the checked radio, so use :checked selector

 $('.trigger').change(function () { $('.content').hide(); $('.' + $('.trigger:checked').data('rel')).show(); }).change(); //Show content on page load 

Fiddle

Thanks @tushar With some structure changes, you can achieve this using pure CSS.

You can use :checked to select the switch and selector + to select the next span and input siblings, and use display: block; for them.

 .content { display: none; } input:checked + span, input:checked + input { display: block; } 
 <form id='group'> <div> <label> <input type="radio" name="group1" class="trigger" data-rel="abc" checked />ABC <span class="abc content"> <span>I belong to ABC</span> <input type="button" value="ABC" /> </span> </label> </div> <br> <div> <label> <input type="radio" name="group1" class="trigger" data-rel="xyz" />XYZ <span class="xyz content"> <span>I belong to XYZ</span> <input type="button" value="XYZ" /> </span> </label> </div> </form> 
+4
source

just remove .change(); from your js

 $('.trigger').change(function () { $('.content').hide(); $('.' + $('.trigger:checked').data('rel')).show(); }); 

Your updated script

+1
source

Source: https://habr.com/ru/post/1235334/


All Articles