-1

I have following code

<div class="subjects-list">
  <input type="checkbox" class="subject" value="Math">
</div>

<div class="subject-list">
  <input type="checkbox" class="subject" value="Sports">
</div>

I have checkbox value. I want to add class"taken" to div with "subjects-list" class and input with the specified value. What if the perfect way to do this?

for example if value "Sports"

<div class="subjects-list">
  <input type="checkbox" class="subject" value="Math">
</div>

<div class="subject-list taken">
  <input type="checkbox" class="subject" value="Sports">
</div>

Solution

I run in on ready document:

  $('input[type=checkbox]').each(function(index,item){
       var subject = $(item).val();
       if(subject == 'Sports'){
            $(item).parent().addClass('taken');
        }
    });

1 Answers1

0

If you want to add class to parent to div when checked then do this.

$('input[type=checkbox']).on('change', function() {
  if ($(this).prop('checked') {
    $(this).parent().addClass('taken');
  } else {
    $(this).parent().removeClass('taken');
  }
});

Or If you want to just add class by value

$('input[type=checkbox']).each(function(index, item) {
  var subject = $(item).val();
  if (subject == 'Sprots') {
    $(item).parent().addClass('taken');
  }
});
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
chuu
  • 128
  • 6