-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');
        }
    });
2
  • $(".subject-list").addClass("taken")??? Commented Jan 9, 2020 at 8:44
  • Note in the duplicate that this is the best answer Commented Jan 9, 2020 at 8:48

1 Answer 1

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');
  }
});
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.