Paint input by clicking the checkbox

Asked

Viewed 157 times

1

I need you to click on checkbox paint the background of tr and input.

In the code below it paints only the background of tr and clicking anywhere from 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>

2 answers

2


Kevin made a solution only with CSS she does not use the "design" of input default browser, but sometimes it suits you. If you have any questions tell me that I can give you more explanations of how it works. But the main thing here is to keep the 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>

1

With CSS you can do that.

When the tr have the class clicado, input will take 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>

Browser other questions tagged

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