Reputation: 95
I have a database with clients and each client has its own color assigned. I'm trying to charge the client and its color in a table. I'm using jQuery. The thing is when I charge the data in the table, it only charges the color of the last client for all of them (except for the one that belongs that color). This is my code:
HTML:
<table id="tablaClientes" class="tablaClientes">
<thead>
<tr>
<th hidden>ID</th>
<th>Nombre del Cliente</th>
<th>Color</th>
<th>Editar Cliente</th>
</tr>
</thead>
<tbody>
</tbody>
</table><br/><br/>
JS:
$(function getClientes(){
$.getJSON(URL)
.done(function(data) {
console.log(TAG + "AJAX GET CLIENTE")
console.log(TAG + "typeof data: " + typeof data + " data: " + data);
for(let cli of data){
let id = cli.id_cliente;
let nombre = cli.nombre_cliente;
let color = cli.color_cliente;
console.log(TAG + "id cliente: " + id);
console.log(TAG + "nombre cliente: " + nombre);
console.log(TAG + "color cliente: " + color);
let tr = $('<tr id="filaCliente"> <td hidden id="idCliente">' + id + '</td> <td>' + nombre
+ '</td>' + '<td><div class="color"></div></td> <td><button id="btnEditar">Editar</button></td> </tr>');
$('.color').css({"background":color});
$("#tablaClientes tbody").append(tr);
}
});
});
CSS:
.color {
width: 25px;
height: 25px;
border: 1px;
}
And this is what i get: the table with clients and colors
As you can see in the image all of them have the same color, except the last one 'UPV' that is the one that color belongs. I know that's because it changes all td with the class '.color' with the last client's color in the AJAX call. But I don't know how to fix this. And I don't understand why it fills all the td except for the last client.
Also tried with $('.color', this).css({"background":color});
but it's not working. And if I change the CLASS property by ID, it only fills the first client color with the color of the last one.
Upvotes: 0
Views: 6632
Reputation: 1446
A quick fix here would be: instead of using class, you can just insert a inline style.
Change:
<td><div class="color"></div></td>
to:
<td><div style="background:' + color + '"></div></td>
Upvotes: 1
Reputation: 1326
In this line:
$('.color').css({"background":color});
You changed all .color
divs.
You need this:
tr.find('.color').css({"background":color});
Upvotes: 0
Reputation: 646
You can provide specific class for the "td".
or else you can style the "td" with CSS selectors.
Ex:
tr td:nth-child(1){color:red;}
tr td:nth-child(2){color:blue;}
tr td:nth-child(3){color:green;}
Or you can use add or even
tr td:nth-child(odd){color:red;}
tr td:nth-child(even){color:blue;}
you can also use this
tr td:nth-child(4n+1){color:green}
Upvotes: 0