A way to do this using an object with styles.
You can check if it is checked with $(this).is(":checked")
, which returns true (if checked) or false (if not checked).
The object opts
has a function with the styles between keys {}
that returns the values depending on the value in the i
parameter of the function, alternating the properties using ternaries ( learn more about ternary operator ).
One of the advantages of ternary is to avoid repeating code 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 must separate the values with colon :
instead of comma.
Another thing to note is that you can write the names of the properties outside the quotation marks, but if there is a hyphen -
, you must remove it and write the first letter after the capitalization:
'background-color' -> backgroundColor
Example:
$('.linhaCdSRotinaTurma').css({
backgroundColor:'#fff',
cursor:'auto'
});
See the code working:
$('.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><divclass="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>