1
votes

I was trying to code jquery/JS logic for hide/show description based on radio button being checked or not. If the radio button is checked on page load, i want the description associated with that radio button to load. But the default one of the either has to selected/checked

I did try to code with .change and click methods inside ready(). But was not successful

I have only two radio buttons, I'm not a Javascript/jquery person. Any input is appreciated. This is an example

<div id="ServiceSelection">     
 <input type="radio" name="Service" checked="Checked" value="B"> Option 1
  <br>
 <input type="radio" name="Service" value="P"> Option 2
  <br>
  <div id="DivB" style="display:none" class="desc">B  Description goes here </div>
 <div id="DivP" style="display:none" class="desc">P Description goes here </div>    
</div> 

Edited DIV:

<div id="ServiceSelection">     
<input type="radio" name="Service" checked="Checked" value="B"> Option 1
<br>
<div id="DivB" style="display:none" class="desc">B  Description goes here </div>
<input type="radio" name="Service" value="P"> Option 2
<br>
<div id="DivP" style="display:none" class="desc">P Description goes here </div>    
</div> 

Thanks in advance J

3

3 Answers

2
votes
if($('input[name=Service]').is(':checked')){ //is it checked?
    var v = $('input[name=Service]:checked').val(); //get the value
    $('div[id$='+v+']').show(); //target the end of selector, and match it to our value
}

$('input[name=Service]').on('click', function(){
   $(this).parent().find('div').hide(); //hide the divs...
   $('div[id$='+$(this).val()+']').show(); //show the div based on our value again..
});    

fiddle

1
votes

Try this:

function ShowData(evt) {
    var val = $("input[name=Service]:checked").val();
    if (val == 'B') {
        $('#DivB').show();
        $('#DivP').hide();
    } else {
        $('#DivP').show();
        $('#DivB').hide();
    }
}

$('input[name=Service]:radio').change(ShowData);
ShowData();

DEMO HERE

1
votes

I'd suggest:

// hide the div elements with JavaScript, so they're visible to those
// users with JavaScript disabled:
$('#ServiceSelection div[id]').hide();

// select the radio input elements and bind to the change event
$('input:radio').change(function(){
    // find the element whose id is equal to 'Div' + the value of the radio,
    // show that div, hide the sibling div elements
    $('#Div' + this.value).show().siblings('div').hide();
// filter the radio elements to find the one that's checked, and trigger the change event
}).filter(function(){return this.checked; }).change();

JS Fiddle demo.

References: