bldev
bldev

Reputation: 137

How to add class based on input attribute in jquery?

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>

Upvotes: 1

Views: 1469

Answers (2)

poushy
poushy

Reputation: 1134

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/

Upvotes: 0

Ohgodwhy
Ohgodwhy

Reputation: 50787

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

Upvotes: 1

Related Questions