Background-color Td radioButton

1

I'm having trouble resolving this situation. I have in my table a list with a radio button, it happens that when selecting an option, it works perfectly coloring the background of the td, but when I select the second option it also selects the background of another td having 2 colored options and only one radio button, simulating a checkbox that is not my case. If you can help me, I'll be very grateful. Thanks!

$(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');
  }
  });
});
.clicado{background: #000; color:#fff;}
.desclicado{background: #fff; color: #000;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script><table><thead><tr><th>#</th><th>Nome</th></tr></thead><tbody><tr><td><inputid="id_bairro" name="id_bairro" value="1" type="radio"/>01</td>
      <td>teste 01</td>
    </tr>
    <tr>
      <td><input id="id_bairro" name="id_bairro" value="2" type="radio"/>01</td>
      <td>teste 02</td>
    </tr>
  </tbody>
</table>
    
asked by anonymous 25.04.2018 / 05:01

2 answers

1

I would like to say that your code is very full of problems, and it would be better to redo it. This .desclicado class is unnecessary since you just need to return the element to its initial situation by removing the .clicado class (unless you are planning to do something later with the .desclicado class. ).

$(document).ready(function(){
   $('[name="id_bairro"]', 'table').click(function(){

      // removo a classe de todas as TRs
      $('tr', 'table')
      .removeClass("clicado");

      // adiciono a classe a TR onde o radio foi clicado
      $(this)
      .closest("tr")
      .addClass("clicado");
      
   });
});
.clicado{background: #000; color:#fff;}
.desclicado{background: #fff; color: #000;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><table><thead><tr><th>#</th><th>Nome</th></tr></thead><tbody><tr><td><inputid="id_bairro" name="id_bairro" value="1" type="radio"/>01</td>
      <td>teste 01</td>
    </tr>
    <tr>
      <td><input id="id_bairro" name="id_bairro" value="2" type="radio"/>01</td>
      <td>teste 02</td>
    </tr>
  </tbody>
</table>
    
25.04.2018 / 05:13
0

Problem solved, before closing this topic, I would like to know how to add the code below without conflict: (the code below selects the radioButton by clicking on top of the td)

$("td").click(function(e) {
    var checkbox = $(':radio', $(this).parent()).get(0);
    var checked = checkbox.checked;
    if (checked == false){ 
		checkbox.checked = true;
    }else { 
		checkbox.checked = false;
	}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Thank you!

    
25.04.2018 / 15:17