Home > database >  Error occuring only on Sunday for general simple weektable
Error occuring only on Sunday for general simple weektable

Time:05-22

Im working on a general table that highlights the current day of the week. It worked on all days except for Sunday, today. Its now broken and it returns the following error:

enter image description here

Apparently the code is not robust at all? Should there be a completely different way of writing this? PS. the if statement is to prevent the code from firing for all the pages that do not contain such a worktable.

https://jsfiddle.net/mxopg6fz/

workday();

function workday(){
    if (document.getElementById("weekdagtabel") !== null){
        var d = new Date().getDay();
        document.getElementById("day-" d).classList.add("today");
    }
}
.today {
  font-weight: bold;
}

.open {
  background-color: green; 
}

.closed {
  background-color: red; 
}



table {
    border-collapse: collapse;
    width: 100%;
    border-spacing: 0;
    margin: .5em 0;
}

th, td {
    padding: 1em;
    text-align: left;
    border-bottom: 1px solid #ddd;
    border-color:black;
    border-style:solid;
    border-width:1px;
    overflow:hidden;
    word-break:normal;
}

tr:hover {background-color: #EEE}
<table>
    <tbody id="weekdagtabel">
        <tr id="day-1">
            <td>Monday</td>
            <td>08:00 - 20:00</td>
        </tr>
        <tr id="day-2">
            <td>Tuesday</td>
            <td>08:00 - 20:00</td>
        </tr>
        <tr id="day-3">
            <td>Wednesday</td>
            <td>08:00 - 20:00</td>
        </tr>
        <tr id="day-4">
            <td>Thursday</td>
            <td>08:00 - 20:00</td>
        </tr>
        <tr id="day-5">
            <td>Friday</td>
            <td>08:00 - 20:00</td>
        </tr>
        <tr id="day-6">
            <td>Saturday</td>
            <td>Closed</td>
        </tr>
        <tr id="day-7">
            <td>Sunday</td>
            <td>Closed</td>
        </tr>
    </tbody>
</table>

CodePudding user response:

Check this line of code:

var d = new Date().getDay();

d variable gets values from 0 to 6 (0 for Sunday, 1 for Monday, etc)

but you have ids from 1 to 7 in your html (day-1 ... day-7)

For Sunday, your code is looking for id day-0 here:

document.getElementById("day-" d)

but it is not present in your html, you have day-7 instead

Use day-0 id for Sunday instead of day-7, or adjust your d variable in your code, to reflect existing ids in your html file.

  • Related