Reputation: 53
I have a table of items. How do I make a cell turn color, lets say to red if the item is equal to 0
The ID of the table is myTable. I don't know how I should do this in javascript. I have added an id:
<td id="quantity"><?php echo e(($row['Quantity'])); ?></td>
function ChangeColor(){
.... //what goes here
}
Upvotes: 0
Views: 558
Reputation: 665
This is a code javascript
if you want use a javascript
.
Need a call with cell
of th
then give a cell.innerHTML
.
This example
var th = document.querySelectorAll('th')
for (let cell of th) {
if(cell.innerHTML === '6'){
cell.style.backgroundColor = 'green'
}
if(cell.innerHTML === '0'){
cell.style.backgroundColor = 'red'
}
}
table {
margin-bottom: 1em;
border-collapse: collapse;
}
td,
th {
padding: .25em .5em;
border: 1px solid #333;
font: .75em "Verdana";
}
<table id="Table">
<tbody>
<tr>
<th>Data</th>
<th>Number</th>
<th>Total</th>
</tr>
<tr>
<th>Product</th>
<th>0</th>
<th>6</th>
</tr>
<tr>
<th>Product2</th>
<th>5</th>
<th>0</th>
</tr>
</tbody>
</table>
Upvotes: 0
Reputation: 698
Use class
instead of id
<td class="quantity"><?php echo e(($row['Quantity'])); ?></td>
then select the <td>
that has the "quantity" class, and evaluate their content
document.querySelectorAll('td.quantity').forEach(e => {
if( Number(e.textContent) < 0)
e.classList.add('negativeQtty')
})
then declare a css class negativeQtty
.negativeQtty {
background-color: red;
}
Upvotes: 1
Reputation: 119
You can use Bootstrap background class
<td id="quantity"class="p-3 mb-2 bg-primary text-white"><?php echo e(($row['Quantity'])); ?></td>
Upvotes: 0
Reputation: 514
You'd want to do this in PHP at run time, not in JavaScript like you hint at:
For example,
<?php
$backgroundColor = $row['Quantity'] == 0 ? 'red' : 'none';
echo '<td id="quantity" style="background-color: ' . $backgroundColor .'">' . e(($row['Quantity'])) . '</td>';
?>
Upvotes: 2