Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save hedleysmith/1f54c25c78ae4148c875 to your computer and use it in GitHub Desktop.

Select an option

Save hedleysmith/1f54c25c78ae4148c875 to your computer and use it in GitHub Desktop.
Add selected and not-selected classes to radio inputs parent elements for checked and not-checked radio inputs in jQuery
// Load selected & not-selected classes when page loads
$('input[type=radio]').filter(':checked').parent().addClass('selected');
$('input[type=radio]').filter(':not(":checked")').parent().addClass('not-selected');
// When radio buttons are changed add classes
$('form').once('selected-radio-listen').on(
"change",
"input[type=radio]",
function () {
// Get all related inputs.
var name = $(this).attr('name');
// Non-selected items.
$('input[name="' + name + '"]').parent().removeClass('selected');
$('input[name="' + name + '"]').parent().addClass('not-selected');
// The selected item.
$('input[name="' + name + '"]').filter(':checked').parent().addClass('selected');
$('input[name="' + name + '"]').filter(':checked').parent().removeClass('not-selected');
}
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment