0

I'm working on my portfolio website and need some help with a bit jQuery code. I want a parent class to react to the checkbox in it. In this case, the background color needs to change to #000 when the checkbox is active/checked.

I don't know what line of code to add to make my class react to the checkbox. I've searched on google on how to do it but didn't get much wiser. It's probably a really small thing but I would hope to get some help from you guys.

$("input[type='checkbox']").change(function() {
  if ($(this).is(":checked")) {
    $(this).parent();
  } else {
    $(this).parent();
  }
});
.product {
  background-color: #ccc;
  /* needs to change to #000 when active */
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>

<div class="product">
  <input class="check" type="checkbox" name="logo"> Logo 
</div>

2
  • Why does this question has "reactjs" tag? Commented Apr 24, 2019 at 13:25
  • probably a typing error, hope it doesn't bother you too much... What i meant with it is that the parent needs to react to the checkbox, hence the tag 'react' Commented Apr 24, 2019 at 13:28

1 Answer 1

4

Basically you create a second (more specific) css selector for the active state, then you use your jQuery to toggle that state/class based on the checkbox value.

https://jsbin.com/betafupogu/1/edit?html,css,js,output

CSS

.product {
  background-color: #ccc; /* needs to change to #000 when active */
}

.product.active {
  background-color: #000; 
}

jQuery

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
    <script>

        $("input[type='checkbox']").change(function(){
    if($(this).is(":checked")){
        $(this).parent().addClass('active'); 
    }else{
        $(this).parent().removeClass('active'); 
    }
});

</script>
Sign up to request clarification or add additional context in comments.

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.