keshinpoint
keshinpoint

Reputation: 1001

Triggering event on radio button click

I have a few radio buttons, one of which is the 'other' button. If a user clicks 'other' I want to show a text box asking for more info. This is my HTML and JS:

    <div class="radio">
    <label><input type="radio" name="optradio">Friend</label>
    </div>
    <div class="radio">
    <label><input type="radio" name="optradio"> Worked together </label>
    </div>
    <div class="radio">
    <label><input type="radio" name="optradio"> Studied together</label>
    </div>
    <div class="radio">
    <label><input type="radio" name="other-radio" id="connection-invite-other-radio"> Other </label>
    </div>

   <div class="form-group" id="connection-invite-other">

    <input type="text" class="form-control" >
    </div>

JS:

$(document).ready(function(){


    if($('#connection-invite-other-radio').is(':checked')) {        
        $('#connection-invite-other').show();
        console.log("hi");
    }

    else {
        $('#connection-invite-other').hide();
    }

});

This however isn't working. Please help me understand if I'm doing something wrong. Thanks!

Upvotes: 0

Views: 1587

Answers (2)

eisbehr
eisbehr

Reputation: 12452

  1. The radio needs to have the same name, in your case optradio.
  2. You need to use a change event listener on all radio elements.

$(document).ready(function() {
  $('input[type=radio]').change(function() {
    if ($('#connection-invite-other-radio').is(':checked')) {
      $('#connection-invite-other').show();
    } else {
      $('#connection-invite-other').hide();
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="radio">
  <label>
    <input type="radio" name="optradio">Friend</label>
</div>
<div class="radio">
  <label>
    <input type="radio" name="optradio">Worked together</label>
</div>
<div class="radio">
  <label>
    <input type="radio" name="optradio">Studied together</label>
</div>
<div class="radio">
  <label>
    <input type="radio" name="optradio" id="connection-invite-other-radio">Other</label>
</div>
<div class="form-group" id="connection-invite-other">
  <input type="text" class="form-control">
</div>

Upvotes: 2

Mairaj Ahmad
Mairaj Ahmad

Reputation: 14604

You need to call change event of radio button to show hide div.

$(document).ready(function(){

   $('#connection-invite-other-radio').change(function(){
    if($(this).is(':checked')) {        
        $('#connection-invite-other').show();
        console.log("hi");
    }

    else {
        $('#connection-invite-other').hide();
    }
   });    
});

Upvotes: 0

Related Questions