user3733831 user3733831 - 5 years ago 168
Javascript Question

Show / Hide contents base on radio button seelection

I am trying to toggle a content DIV base on the selection of radio buttons.

HTML for radio button.

<div class="row-fluid">
<label class="radio">
<input type="radio" name="account" id="yes" value="yes" checked>
Yes, I have an existing account
</label>
<label class="radio">
<input type="radio" name="account" id="no" value="no">
No, I don't have an account
</label>
</div>


Content DIV

<div id="account_contents">
<p>This is account contents.......</p>
</div>


This is how I tried it in jquery.

$('#no').bind('change',function(){
$('#account_contents').fadeToggle(!$(this).is(':checked'));
$('#account_contents').find("input").val("");
$('#account_contents').find('select option:first').prop('selected',true);
});


But it doesn't work for me correctly. Here I want to show this content DIV only if user don't have an account.

Can anybody tell me how to fix this problem.
Thank you.

Answer Source

seems you need .on('change') for radio buttons not just for one of them

$('input[type="radio"][name="account"]').on('change',function(){
  var ThisIt = $(this);
  if(ThisIt.val() == "yes"){
       // when user select yes
       $('#account_contents').fadeOut();
  }else{
       // when user select no
       $('#account_contents').fadeIn();
       $('#account_contents').find("input").val("");
       $('#account_contents').find('select option:first').prop('selected',true);
  }
});

Working Example

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download