Question

I need to add/remove a generic class (something like .is-checked) on a series of radio buttons and checkboxes. Here's the code I have:

$(function () {
  $('input[type="checkbox"], input[type="radio"]').each(function () {
    $(this).on('click', function () {
      $(this).parent().wrap('<div>').unwrap();  
        // works great for checkboxes, but not for radios
        if ($(this).prop('checked')) {
          $(this).addClass('is-checked');
        } else {
          $(this).removeClass('is-checked');
        }
    })
  })
})

This works perfectly on checkboxes, but on the class that gets added to radio buttons never gets removed. Thoughts? Ideas?

EDIT I accidentally neglected to mention that this script will be conditionally loaded for IE8 since the ':checked' pseudo selector is not supported. The entire feature works perfectly fine in everything but IE8, so this is a crutch for that browser and the poor users stuck dealing with it. In the end, the 'is-checked' class will trigger the same CSS that the :checked selector does.

Was it helpful?

Solution

I now see what you're after. The problem is with this line:

$(this).removeClass('is-checked');

It's only removing .is-checked from the element that was clicked. This works for checkboxes, but since radios work differently, this isn't going to work. To solve this, do something like this:

$(function () {
    $('input[type="checkbox"], input[type="radio"]').on('click', function () {
        $(this).parent().wrap('<div>').unwrap();
        $('input[type="checkbox"], input[type="radio"]').each(function () {
            $(this).is(':checked') ? $(this).addClass('is-checked') : $(this).removeClass('is-checked');
        });
    });
});

http://jsfiddle.net/xzNPh/4/

OTHER TIPS

Try to use native property:

$('input[type="checkbox"], input[type="radio"]').on('click', function () {
      $(this).parent().wrap('<div>').unwrap(); 
      if (this.checked) {
          $(this).addClass('is-checked');
      } else {
          $(this).removeClass('is-checked');
      }    
});

How about:

var inputs = $('input[type="checkbox"], input[type="radio"]');
inputs.on('click', function () {
    $(this).parent().wrap('<div>').unwrap();  
    inputs.removeClass('is-checked');
    $(this).toggleClass('is-checked', $(this).prop('checked', true));
});

You haven't explain what's it for, so I won't venture a guess if you even need that code. Eg. if it's only styling then maybe css would do just fine here.

And a fiddle

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top