Selecionando outras células com o mesmo conteúdo
by Rodrigo Portillo
HTML
<select id="selectNome">
<option value="-1">Selecione</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
</select>
<button id="btnLimpar">
Limpar
</button>
<div class="area-tabela">
<table id="minhaTabela">
<thead>
<tr>
<th>
Valor 1
</th>
<th>
Valor 2
</th>
<th>
Valor 2
</th>
</tr>
</thead>
<tbody>
<tr>
<td>0-5</td>
<td>1-3</td>
<td>2-3</td>
</tr>
<tr>
<td>1-2</td>
<td>3-3</td>
<td>8-2</td>
</tr>
<tr>
<td>4-1</td>
<td>1-2</td>
<td>2-4</td>
</tr>
<tr>
<td>5-5</td>
<td>0-7</td>
<td>8-8</td>
</tr>
</tbody>
</table>
</div>
CSS
body{
font-family: sans-serif;
}
.area-tabela table{
margin-top:20px;
border-spacing: 0;
border: 1px solid grey;
width: 100%;
}
.area-tabela table td, .area-tabela table th{
width:80px;
padding: 5px 10px;
font-size: 14px;
cursor: pointer;
transition: all .3s linear;
-moz-transition: all .3s linear;
-webkit-transition: all .3s linear;
}
.area-tabela table td:hover{
background-color: lightyellow;
}
.area-tabela table th{
background-color: grey;
color: white;
font-weight: normal;
}
.area-tabela table tr:nth-child(even) td{
background-color: #efefef;
}
.area-tabela table tr td.highlight{
background-color: #1361bf;
color: white;
}
JavaScript
let valoresSelecionados = localStorage.valoresSelecionados;
if(valoresSelecionados == undefined){
valoresSelecionados = [];
}else{
valoresSelecionados = valoresSelecionados.split(",");
}
function highlightSel(number){
valoresSelecionados.push(number);
localStorage.valoresSelecionados = valoresSelecionados;
document.querySelectorAll(".area-tabela table tr td").forEach((td)=>{
if(eval(td.innerHTML.trim().replace("-", "+")) == number){
td.classList.add("highlight");
}
});
}
document.querySelector("#selectNome").addEventListener("change", ()=>{
highlightSel(parseInt(event.target.value));
});
function highlightClick(word){
valoresSelecionados.push(word);
localStorage.valoresSelecionados = valoresSelecionados;
console.log(localStorage.valoresSelecionados);
document.querySelectorAll(".area-tabela table tr td").forEach((td)=>{
if(td.innerHTML.trim().toLowerCase() == word.trim().toLowerCase()){
td.classList.add("highlight")
}
});
}
document.querySelectorAll(".area-tabela table tr td").forEach((td)=>{
td.addEventListener("click", ()=>{
highlightClick(event.target.innerHTML);
});
});
function limpar(){
document.querySelector("#selectNome").value = -1;
document.querySelectorAll(".area-tabela table tr td").forEach((td)=>{
td.classList.remove("highlight")
});
}
document.querySelector("#btnLimpar").addEventListener("click", limpar);
function carregarValores(){
console.log(valoresSelecionados);
valoresSelecionados.forEach((item)=>{
document.querySelectorAll(".area-tabela table tr td").forEach((td)=>{
if(td.innerHTML.trim().toLowerCase() == item){
td.classList.add("highlight")
}
});
});
}
carregarValores();