Change table value depending on the current time

Viewed 60

I would like to change the value on the third column depending on the time. By the way, I created this table on app script.

For example:

  1. When the time hits 1:00 PM the status must be "Lunch" (1 hr)
  2. When the time hits 6:00 PM the status must be "Shift Ended".

I'm new to coding and on the process of learning javascript.

Is there a way to do it?

<style>
table {
  font-family: arial, sans-serif;
  border-collapse: collapse;
  width: 100%;
}

td, th {
  border: 1px solid #dddddd;
  text-align: left;
  padding: 8px;
}

tr:nth-child(even) {
  background-color: #dddddd;
}
</style>
<h2>Employee Status</h2>

<table>
  <tr>
    <th>Employee</th>
    <th>Shift</th>
    <th>Status</th>
  </tr>
  <tr>
    <td>Juan Dela Cruz</td>
    <td>9:00 AM - 6:00 PM</td>
    <td>Working</td>
  </tr> 
</table>

1 Answers

Simplest way to edit the value in the table should be by accessing the table itself via javascript. For us to do that, you need to know what is the id of the table. In my test, I assigned "employee-status" to the table

<h2>Employee Status</h2>

<table id = "employee-status">
  <tr>
    <th>Employee</th>
    <th>Shift</th>
    <th>Status</th>
  </tr>
  <tr>
    <td>Juan Dela Cruz</td>
    <td>9:00 AM - 6:00 PM</td>
    <td>Working</td>
  </tr> 
</table>

As for the javascript, we need to get that table with the unique id. Then get the current time using Date() then use getHours() to get the specific hour.

Conditions below

var table = document.getElementById("employee-status");
var date = new Date();
var hour = date.getHours();

// The data we need to update is in the 2nd row, 3rd column
// Thus we need to update 'table.rows[1].cells[2].innerHTML' value.

if(hour < 9) {
    // Feel free to change this status since if not added
    // 8 AM will result into "Working" status
    table.rows[1].cells[2].innerHTML = 'Shift Not Started';
}
else if(hour >= 13 && hour < 14) { 
    // Between 1 PM and 2 PM will be 'Lunch (1 hr)'
    table.rows[1].cells[2].innerHTML = 'Lunch (1 hr)';
}
else if(hour > 17) { 
    // Beyond 6 PM will be 'Shift Ended'
    table.rows[1].cells[2].innerHTML = 'Shift Ended';
}

Sample output for different times of the day:

sample output

There are many ways to have it changed, this will be the most direct way in changing it via javascript.

Related