Paint input when clicking the checkbox

1

I need to just click on checkbox to paint background on tr and on input.

In the code below, it paints only background of tr and clicking anywhere in tr .

<html>
<head>
<script src="//code.jquery.com/jquery-2.1.0.min.js"></script>
  <meta charset="utf-8">
  <title>JS Bin</title>

  <script>
    $(document).ready(function(){
      $('.table tr').click(function(){
        $trClass = $(this).attr('class');
        if ($trClass == undefined || $trClass == 'desclicado'){
          $(this).attr('class', 'clicado');
        } else {
          $(this).attr('class', 'desclicado');
        }
      });
    });
  </script>

  <style>
    .clicado{background: #000; color:#fff;}
    .desclicado{background: #fff; color: #000;}
  </style>

</head>
<body>
  <table class="table">
     <td><input type="text"></td>
     <td><input type="text"></td>
     <td><input type="text"></td>
     <td><input type="checkbox"></td></tr>
  </table>
</body>
</html>
    
asked by anonymous 01.06.2018 / 14:58

2 answers

2

Kevin made a solution with CSS only, she does not use the "design" of the input default of the browser, but sometimes it caters to you. If you have any questions, let me know if I can give you more explanation of how it works. But the main thing here is to keep input out of tabela for the CSS rule to work, and label will play the role of checkbox

label  {
    width: 12px;
    height: 12px;
    border: 1px solid;
    position: relative;
    display: inline-block;
    cursor: pointer;
    background: #fff;
    color: #000;
}
[type="checkbox"] {
    display: none;
}
#btn:checked + table label::after  {
    content: "✔";
    position: absolute;
    top: -5px;
    left: 0;
}
#btn:checked + table:not(label), #btn:checked + table input {
    background-color: #000;
    color: #fff;
}
<input id="btn" type="checkbox">
<table class="table">
    <tr>
        <td><input type="text">123</td>
        <td><input type="text">abc</td>
        <td><input type="text">123</td>
        <td><label for="btn"></label></td>
    </tr>
</table>
    
01.06.2018 / 15:23
1

With CSS you can do this.

When tr has class clicado , the input will pick up the styles that are defined

<style>
  .clicado{background: #000; color:#fff;}
  .desclicado{background: #fff; color: #000;}
  /* o novo estilo */
  .clicado input { background: blanchedalmond; }
</style>

Edit You can improve your Javascript too. Take a look at parents () and toggleClass ()

<script>
$(document).ready(function(){
  $('input[type=checkbox]').change(function(){
    $checkbox = $(this);
    $tr = $(this).parents('tr');
    $tr.toggleClass("clicado", $checkbox.checked);
  });
});
</script>
    
01.06.2018 / 15:24