Zikaynam Zikaynam - 11 days ago 5
CSS Question

changing label class for radio button groups

below is a code snippet of radio button group using a bootstrap template. But what I am trying to do is change the class portion of the radio button every time the option is toggled (i.e. radio button is checked the label class would be 'btn btn-primary' and if unchecked label class would be 'btn btn-default' ). Anyone knows how to accomplish this?

<body>
<div class = "form-group">
<label class = "control-label col-md-3 col-sm-3 col-xs-12">Gender</label>

<div class = "col-md-6 col-sm-6 col-xs-12">
<div id = "gender" class = "btn-group" data-toggle = "buttons">
<label class = "btn btn-default" data-toggle-active-class = "btn-primary" data-toggle-passive-class = "btn-default">
<input type = "radio" name = "gender" value = "male"> &nbsp; Male &nbsp;
</label>

<label class = "btn btn-primary" data-toggle-class = "btn-primary" data-toggle-passive-class = "btn-default">
<input type = "radio" name = "gender" value = "female"> Female
</label>
</div>
</div>
</div>
</body>

Answer

You can do something like this:

 $('input:radio').change(function(){
      var $self = $(this);
      if ($self.prop('checked')) {
      $('input[type=radio]').parent().removeClass('btn-primary');
         $self.parent().addClass('btn-primary');
      } else {
         $self.parent().removeClass('btn-default');
      }
   });

Here working fiddle code: https://jsfiddle.net/3r602pcg/

Comments