最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

javascript - when checkbox is checked, change background color of div - Stack Overflow

matteradmin6PV0评论

What I'm trying to do is when the checkbox is checked, change the background color of the div, and when it's unchecked, remove the background color. How can I do this using jquery?

<div class="checkbox-container">
    <input type="checkbox" class ="checkbox-border" id="personal-info-checkbox">
      <label for="personal-info-checkbox"> Mark as reviewed and acknowledged
      </label>
 </div>

using parent selector and .removeclass I do not know how to select my div and turn the color off and on using jquery.

What I'm trying to do is when the checkbox is checked, change the background color of the div, and when it's unchecked, remove the background color. How can I do this using jquery?

<div class="checkbox-container">
    <input type="checkbox" class ="checkbox-border" id="personal-info-checkbox">
      <label for="personal-info-checkbox"> Mark as reviewed and acknowledged
      </label>
 </div>

using parent selector and .removeclass I do not know how to select my div and turn the color off and on using jquery.

Share Improve this question asked Dec 7, 2022 at 16:43 AdambAdamb 295 bronze badges 2
  • 2 What have you tried, in order to solve this yourself? Where's your (relevant) "minimal reproducible example" code? What went wrong - and in what way - with that code, were there any errors reported? – David Thomas Commented Dec 7, 2022 at 16:45
  • To give you a direction to start looking at, you need to set an event listener on your checkbox and, since using jQuery, you can use the toggleClass() method on your container element: api.jquery./toggleclass – Jeremy Harris Commented Dec 7, 2022 at 16:49
Add a ment  | 

5 Answers 5

Reset to default 5

You don't need jQuery for this
You can do this only with css.

    .checkbox-container:has(input:checked) {
    background-color: red;
}

:has pseudo class is supported in chromium, safari.
For firefox, need to enable flag. know more at mdn ::has pseudo class

Add a change event listener to the input that sets its closest parent div's background color based on whether it is checked:

$('input[type="checkbox"]').change(function(){
  $(this).closest('div').css('background-color', this.checked ? 'green' : 'white')
})
<script src="https://cdnjs.cloudflare./ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="checkbox-container">
    <input type="checkbox" class ="checkbox-border" id="personal-info-checkbox">
      <label for="personal-info-checkbox"> Mark as reviewed and acknowledged
      </label>
 </div>

Here's an example of how you can do this

$(function() {
  $("input[type=checkbox]").click( () => {
    $("div").toggleClass("background");
  })
});
.background {
  background: blue;
}
<script src="https://cdnjs.cloudflare./ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div style="height:4em;">
Change colors<input type="checkbox" />
</div>

There are a number of ways to do this:

  1. CSS (with limited, as of writing, browser support),
  2. jQuery (among other libraries), and
  3. native JavaScript.

The below example has explanatory ments in the code:

// using jQuery, we select the relevant element via its class, and use the on()
// method to bind the anonymous function as the event-handler for the 'change'
// event:
$('.checkbox-container.with-jQuery').on('change', function(){
  // here we find the <input> element descendant with find(), and then use the
  // is() method to test that element to see if it matches the :checked pseudo-
  // class; this returns a Boolean true/false which is cached in the 'checked'
  // variable:
    let checked = $(this).find('input').is(':checked');
  
  // here we use toggleClass() to toggle the 'checked' class-name on the element,
  // and use the 'checked' variable to ascertain whether the class should be
  // added/retained (if the Boolean is true) or removed/not-added (if the Boolean
  // is false):
    $(this).toggleClass('checked', checked);
});


// using JavaScript we use document.querySelector to retrieve the element
// with the listed classes; and use EventTarget.addEventListener() to bind the
// anonymous Arrow function as the event-handler for the 'change' event:
document.querySelector('.with-JavaScript.checkbox-container').addEventListener('change',(evt)=>{
  // we cache a reference to the current element (the <div>):
    let current = evt.currentTarget,
      // we find the <input> descendant, and access its checked property to
      // obtain a Boolean true (if checked) or false (if not-checked) and
      // store that Boolean in the 'checked' variable:
        checked = current.querySelector('input').checked;
  // here we use Element.classList.add() to add the 'active' class-name,
  // with the checked variable to determine if it should be added/retained
  // (if true) or removed/not-added (if false):
    current.classList.add('active', checked);
});
:root {
  --checkedColor: lime;
}

/* here we select the element via classes, and use :has()
   to check if it has a descendant element which matches
   the enclosed selector: */
.with-CSS.checkbox-container:has(input:checked) {
  /* if so, we set the --checkedColor custom property
     as the background-color of the element: */
  background-color: var(--checkedColor);
}

.with-jQuery.checkbox-container.checked {
  background-color: var(--checkedColor);
}

.with-JavaScript.checkbox-container.active {
  background-color: var(--checkedColor);
}
<!-- each wrapper <div> has a 'with-...' class applied in order to identify which
     approach is being taken: -->
<div class="checkbox-container with-CSS">
  <!-- an id must be unique, to that end - because there are three checkboxes in
       this example - the id has been modified, as has the corresponding <label>
       element's 'for' attribute: -->
  <input type="checkbox" class="checkbox-border" id="personal-info-checkbox1">
  <label for="personal-info-checkbox1"> Mark as reviewed and acknowledged
  </label>
</div>

<div class="checkbox-container with-jQuery">
  <input type="checkbox" class="checkbox-border" id="personal-info-checkbox2">
  <label for="personal-info-checkbox2"> Mark as reviewed and acknowledged
  </label>
</div>

<div class="checkbox-container with-JavaScript">
  <input type="checkbox" class="checkbox-border" id="personal-info-checkbox3">
  <label for="personal-info-checkbox3"> Mark as reviewed and acknowledged
  </label>
</div>

References:

  • Browser patibility:
    • :has().
  • CSS:
    • CSS Custom properties.
    • :checked.
    • :has().
    • var().
  • JavaScript:
    • document.querySelector().
    • Element.classList API.
  • jQuery@
    • is().
    • on().
    • toggleClass().

Try this I hope this will help you

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis./ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $("#personal-info-checkbox").click(function(){
    if($(this).is(":checked")){
        $(this).parent().addClass("color-blue");
    }else {
        $(this).parent().removeClass("color-blue");
    }
  });
});
</script>
<style>
 .checkbox-container
 {
     padding:20px;
 }
 .color-blue {
     background-color:blue;
 }

</style>
</head>
<body>

<div class="checkbox-container">
    <input type="checkbox" class ="checkbox-border" id="personal-info-checkbox">
      <label for="personal-info-checkbox"> Mark as reviewed and acknowledged
      </label>
 </div>

</body>
</html>

Post a comment

comment list (0)

  1. No comments so far