Search code examples
jquerycheckboxradio-button

Radio button and checkbox problems


I have this piece of code:

<div class="grey-bg box-top-fix">
  <h4>Item 1</h4>
  <p class="muted-small tempos">From 40 $</p>
  <div class="aboutsocial">
    <label class="radio">
      <input type="radio" name="ws_type" value="1">
      Choose this option </label>
  </div>
</div>

I want to be able to change add this class (grey-bg-selected) into my first (the one with the grey-bg box-top-fix classes).

I use this code:

$(document).ready(function() {
  $('.grey-bg').click(function() {
      $('.grey-bg').removeClass('grey-bg-selected')
      $(this).addClass('grey-bg-selected')
  });
});

I have two problems:

1/ If I do not click on the radio button my parent box take the new class. I want this only if the radio is checked. If the radio button lost the check, remove the class. See the jsFiddle here

2/ With checkbox, it doesn't work because if I click on another checkbox, the first lost the new class. See the jsFiddle here

Could you please help me ?

Thanks.


Solution

  • I don't really understand when you want the class to be added, but if it's when the radio button is clicked, try this:

    $(document).ready(function() {
      $('input[type=radio]').click(function() {
          $('.grey-bg').removeClass('grey-bg-selected')
          $(this).parents('.grey-bg').addClass('grey-bg-selected')
       });
    });