Make a change to a div by checking a checkbox

Asked

Viewed 738 times

3

Does anyone know how I change a div or label by marking a checkbox example have this code here.

<label style="margin-bottom: 10px;">
   <div class="adicionalch bg-yellow">
       Nutella <input type="checkbox" name="adicional[]" value="3.00" id="3.00">
  </div>
</label>

classy bg-yellow, by marking the checkbox, it switches to another class or add some css formatting..

2 answers

4


You can do it like this:

function mudaDiv(el) {
  document.getElementsByClassName("bg-yellow")[0].style.backgroundColor = el.checked ? "blue" : "";
}
<label style="margin-bottom: 10px;">
   <div class="adicionalch bg-yellow">
       Nutella <input type="checkbox" name="adicional[]" value="3.00" id="3.00" onclick="mudaDiv(this);">
  </div>
</label>

3

That’s what you want?

$(function() {
  
  $('.checkbox').change(function() {
     var $that = $(this),
         $div = $that.closest('.bg-yellow');
    
        if ($that.is(':checked')) {
             $div.css('background-color', 'yellow');     
        } else {
            $div.css('background-color', '');
        }
    });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<label style="margin-bottom: 10px;">
  <div class="adicionalch bg-yellow">
    Nutella <input type="checkbox" name="adicional[]" value="3.00" id="3.00" class="checkbox"></div>
</label>

Instead of picking up fur id, I had to create a classe, because the formatting of id of your checkbox is not compatible with jQuery selector.

  • Need to see if he uses jQuery or he forgot to put the tag, ;)

  • 1

    Answer there without jQuery, because I’m lazy ;p

Browser other questions tagged

You are not signed in. Login or sign up in order to post.