A way to do this using an object with the styles.
You check if it’s checked with $(this).is(":checked")
, returning true (if checked) or false (if not checked).
The object opts
has a function with the styles between keys {}
which returns values depending on the value in the parameter i
function, alternating properties using ternary (learn more about ternary operator).
One of the advantages of the ternary is to avoid code repetition when you want to take a value or another based on a conditional. Example:
// se i for true, a cor será #fff, caso contrário será #ccc
i ? '#fff' : '#ccc'
Defining styles between keys {}
using .css
:
Your code can be simplified. You are using .css
for the same element twice:
$('.linhaCdSRotinaTurma').css('background-color','#fff');
$('.linhaCdSRotinaTurma').css('cursor','auto');
Using the keys {}
, you can define multiple properties in a single block, without having to repeat the same element:
$('.linhaCdSRotinaTurma').css({
'background-color':'#fff',
'cursor':'auto'
});
The difference is that in this format you should separate the values with two-points :
instead of a comma.
Another thing to note is that you can write the property names out of quotation marks, but in case there is a hyphen -
, you should remove it and write the first letter after in uppercase:
'background-color' -> backgroundColor
Example:
$('.linhaCdSRotinaTurma').css({
backgroundColor:'#fff',
cursor:'auto'
});
View code in operation:
$('.checkbox-regularC').click(function(){
var opts = function(i){
return {
'background-color': i ? '#fff' : '#ccc',
'cursor': i ? 'auto' : 'not-allowed'
};
}
$('.linhaCdSRotinaTurma')
.css(opts($(this).is(":checked")));
});
.linhaCdSRotinaTurma {
background-color: #cccc;
cursor: not-allowed;
border: 0px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="caixaSelectsTodasCategorias">
<div class="caixaCheckBoxTodasCategorias">
<div class="selecionarTodos">
<input type="checkbox" class='checkbox-regularC'>
</div>
</div>
</div>
<table class="tabelaNovaRotinaSelects" id="table_rotina_default">
<thead>
<tr id="rotinasDefault">
<td class='tituloCdSRotinaTurma'>
Titulo
</td>
</tr>
</thead>
<tbody>
<tr class="linhaCdSRotinaTurma">
<td >Alternativas</td>
</tr>
</tbody>
</table>
Will it be just one or are several on the same screen?
– Sam
It will have only one row tr, right but with several columns
– Jaum
Newton, as a new user, reads this link https://answall.com/tour. to know what to do when asking questions and receiving answers. Abs!
– Sam