Al W Al W - 1 year ago 87
PHP Question

Populating html table from external php to allow highlighting on hover over row

I am trying to populate a html table based on a select box (with staff numbers) changing. The data is being retrieved from a mysql database. I then want to highlight a row when it is hovered over using jquery.

Am I going about this the right way?


<div id="logHistory">
<label id="historyTableLabel">Your Log History</label>
<table id="logTable">
<tr id="headers">
<td>Log Date</td>
<td>Start Time</td>
<td>End Time</td>


$staffNum = isset($_POST['staffNumber']) ? $_POST['staffNumber'] : 0;
if($staffNum > 0)
populateLogHistory($con, $staffNum);

function populateLogHistory($con, $staffNum)
//Retrieve data from entries table
$result = mysqli_query($con, "SELECT EntryID, LogDate, LogType, StartTime, StartDate, FinishTime, FinishDate FROM Entries WHERE StaffNumber=$staffNum");

while($row = mysqli_fetch_array($result))
$entryID = $row['EntryID'];
$logDate = $row['LogDate'];
$logTypeID = $row['LogType'];
$resulting = mysqli_query($con,"SELECT LogType FROM logType WHERE LogTypeID=$logTypeID");
$logTypeStr = mysqli_fetch_array($resulting);
$startDate = $row['StartDate'];
$startTime = $row['StartTime'];
$start = $startDate . " " . $startTime;
$start = new DateTime($start);
$finishDate = $row['FinishDate'];
$finishTime = $row['FinishTime'];
$finish = $finishDate . " " . $finishTime;
$finish = new DateTime($finish);
$duration = $start->diff($finish);

echo "<tr id=".$entryID.">";
echo "<td>".$logDate."</td>";
echo "<td>".$logTypeStr[0]."</td>";
echo "<td>".$startTime."</td>";
echo "<td>".$finishTime."</td>";
echo "<td>".$duration->h."hr ".$duration->i."</td>";
echo "</tr>";

jquery code

//Check the mandatory first
var selectedIndex = $("#staffMember").prop('selectedIndex');
isMandatory(selectedIndex, $(this));

if(selectedIndex != -1)
//If there is a staff number call the select to populate the log history
var staffNum = $("#staffMember").val();
var dataString = 'staffNumber=' + staffNum;

type: "POST",
url: "select.php",
data: dataString,
cache: false,
success: function(html)

Answer Source

Use this CSS for the hovering part:

.datarow:hover {
    background-color: #ccc;

Assuming that you put a class tag to your populated row:

echo '<tr id="'.$entryID.'" class="datarow">';

For the populating part, use .on() for every call so you can still do another call on Javascript DOM elements.

$(document).on("change", "#staffMember", function(){

And if you want to do another event handler on the populated data, let's put it as a class tag instead and the data ($entryID) will be on another data tag.

echo '<tr data-artid="'.$entryID.'" class="datarow">';

So when you try to call it, you can just do:

$(document).on("click", ".datarow", function(){

    var entryid = $(this).attr('data-artid'); /* ENTRY ID OF THE CLICKED ROW */