payal_suthar payal_suthar - 4 months ago 9
HTML Question

To apply css to the elements retrieved from database based on their value in database

Here is what I am trying to do-
I have a MySQL table with fields namely- clientname, urgent, complete.And for displaying the values for this fields I have a html table with fields- Clientname,urgent and complete.Each row consist of clientname ,button for urgent and button for complete.If you click on the button urgent in a table row then that button's color changes to red and if you again click on that button then it again attains its original color. In short,it toggles between two classes.At that moment ,In the database urgent field value gets updated from 0(initial value) to 1.Now when I reload the page I want to display the urgent button with value 1 in red color.i.e. I want to apply css to the elements based on their value in the database.
For now I am able to toggle classes to change the color of urgent button on click and update its value but as soon as I refresh the page it again attains its default color.Please let me know how will I be able to retain its color if its value in database is 1 ,even if i refresh the page.
This is jquery code-

$(".u").click(function () {

$(this).toggleClass("urgent");
var ID = $(this).attr('id');


$.ajax({
type:"post",
url:"urgent.php",
data:{'keyid': ID},
cache: false,
success: function(html){

$("#clientsheet").after(html);
}
});return false;
});


Html code-

<td style='text-align:center;'><button id=".$row['id']." class='u'>U</button></td>


Please let me know if you need more info.
Thanks in advance.
Edited-
this is how i am retrieving my html table data from database-

<?php
include('db.php');
$fetch= mysqli_query($conn,"SELECT * FROM pendingwork ORDER BY clientname asc");

while($row=mysqli_fetch_array($fetch)){
$id = $row['id'];
$newname = $row['clientname'];
echo "<tr id=".$row['id']."class='edit_tr'>";
echo " <td class='edit' id=".$id." name=".$newname.">".$row['clientname']."</td>
<td style='text-align:center;'><button id=".$row['id']." class='u'>U</button></td>
<td></td>
<td style='text-align:center;'><button id=".$row['id']." class='del'>Del</button></td>
</tr>";
}

Answer

Something like:

echo " <td class='edit' id=".$id." name=".$newname.">".$row['clientname']."</td>
               <td style='text-align:center;'><button  id=".$row['id']." class='".($row["urgent"] == 1 ? "class1" : "class2")."'>U</button></td>
               <td></td>
               <td  style='text-align:center;'><button id=".$row['id']." class='del'>Del</button></td>
        </tr>";

This bit is the key:

($row["urgent"] == 1 ? "class1" : "class2")

It checks the value of "urgent" and determines the class to use. If "urgent" is 1, then class1 will be applied, otherwise class2. Obviously replace the class names as appropriate for your application.