1

I have some radio buttons that are not initially setting css where checked = "checked".

Any suggestions what type of jquery statement I could use to apply a class on to checked input radio buttons?

I have also attached my jsfiddle

https://jsfiddle.net/2Lbbf1b4/1/

$(function() {
  $('label.radio-inline input').on('change', function() {
    var name = $(this).attr('name');
    if (true === $(this).prop('checked')) {
      $('[name=' + $(this).attr('name') + ']').parent().removeClass('radio-select');
      $(this).parent().addClass('radio-select');
    }
  });
});


<label class="radio-inline radio-style">
  <input type="radio" checked="checked" name="test1" value="1" class="radio-style">
</label>
<label class="radio-inline radio-style">
  <input type="radio" name="test1" value="2">
</label>
<br>
<label class="radio-inline radio-style">
  <input type="radio" checked="checked" name="test" value="1" class="radio-style">
</label>
<label class="radio-inline radio-style">
  <input type="radio" name="test" value="2">
</label>
1

2 Answers 2

1

You could simplify this a bit and and use jQuery's .is() helper method to check for the checked state of the input and compare it against it's siblings with a same name:

$(function() {
    $('label.radio-inline input').on('change', function() {
        if ($(this).is(':checked')) {
            $('input[name="' + $(this).prop('name') +'"]').not($(this)).parent().removeClass('radio-select');
            $(this).parent().addClass('radio-select');
        }
    });
});

Updated jsFiddle

Sign up to request clarification or add additional context in comments.

Comments

0

You need to set the class on initialization using:

$('label.radio-inline input[type=radio]:checked').parent().addClass('radio-select');

Check the fiddle: https://jsfiddle.net/2Lbbf1b4/4/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.