I created a table from database column name "Do You have passport" user answers in yes or no I want where user answer is yes that row should be green and row where user answer is no that row is white can any one tell me how can I apply css to this table that works dynamically.
<html>
<head>
<style>
table, th, td {
border: 1px solid black;
border-collapse: collapse;
}
</style>
</head>
</html>
<?php
$conn = new mysqli("localhost","root","","db_dat");
$havepassport='';
$sql="SELECT * from upload;
$result = $conn->query($sql);
while($row = $result->fetch_assoc()) {
$havepassport.='<table>'.'<tr>'.'<td>';
$havepassport.=$row['having_passport'];
$havepassport.='</table>'.'</tr>'.'</td>';
echo $havepassport;
}
?>
You are doing it wrong. Your while
add new table
to HTML. So, if you have 100 rows, 100 table
s will be added to DOM instead of rows.
Use following:
PHP
$sql = "SELECT * from upload";
$result = $conn -> query($sql);
$havepassport = '<table>';
while ($row = $result -> fetch_assoc()) {
$passportClass = $row['having_passport'] == 'Yes' ? 'green' : 'red';
// ^^^^^^^^^^^ Getting classname depending on the passport value
$havepassport .= '<tr class='.$passportClass.'>'.
// ^^^^^^^^^^^^^^ Add Class Here
'<td>';
$havepassport. = $row['having_passport'];
$havepassport .= '</td>'.
'</tr>';
}
$havepassport .= '</table>';
echo $havepassport;
CSS:
.green {
background: green;
}
.red {
background: red;
}
checkout this fiddle : https://jsfiddle.net/knkp02Ld/1/
HTML
<table id="mytable">
<tr>
<td>User Name</td>
<td>Yes</td>
</tr>
<tr>
<td>User id</td>
<td>No</td>
</tr>
<tr>
<td>Whatever</td>
<td>Yes</td>
</tr>
</table>
JS
$('#mytable td:contains("Yes")').parent().css('background', 'green');
$('#mytable td:contains("No")').parent().css('background', 'red');
Select all elements that contain the specified text.
docs: https://api.jquery.com/contains-selector/
Edit
Other way you can use .each function like as follows
$('#mytable td').each(function() {
var value = $(this).html();
if (value == "Yes") {
$(this).parent().css("background", "red");
}
});
Try this:
<html>
<head>
<style>
table, th, td {
border: 1px solid black;
border-collapse: collapse;
}
</style>
</head>
</html>
<?php
$conn = new mysqli("localhost","root","","db_dat");
$havepassport='';
$sql="SELECT * from upload;
$result = $conn->query($sql);
$havepassport.='<table>';
while($row = $result->fetch_assoc()) {
$passHaveClass = '';
if($row['having_passport'] =="yes"){
$passHaveClass = "greenColor";
}
$havepassport.='<tr class='.$passHaveClass.'>';
$havepassport.= '<td>'.$row['having_passport'].'</td>';
$havepassport.='</tr>;
}
$havepassport.='</table>';
echo $havepassport;
?>
the greenColor
class having bg color is green.