jlusty
April 19, 2020, 11:28pm
1
Here I have the javascript to display that a student is in grade 3. I need to put the entire array (gradeYears) onto a HTML table and keep my loop going. I need to highlight the grade that the student would be in on the table.
I seem to be able to find the information to take an array and put it in a HTML table but then my loop doesn’t work.
This is the JavaScript I’m using to loop through and find grade.
Grade and Age
var birthDate = new Date(2012, 6, 18, 7, 33);
var today = new Date()
var yearDifference = today.getFullYear() - birthDate.getFullYear();
var gradeYears = [
['Grade 1', 6],
['Grade 2', 7],
['Grade 3', 8],
['Grade 4', 9],
['Grade 5', 10],
['Grade 6', 11]
];
var grade = "";
var counter = 0;
while(counter < 6 && grade == "")
{
var currentValue = gradeYears[counter];
if(currentValue[1] == yearDifference)
{
grade = currentValue[0];
}
counter += 1;
}
document.writeln("I am in grade " + grade);
How do I run the loop and at the same time place the array on the HTML table?
I haven’t got round to commenting, daft o’clock here. I have tried to keep it simple.
I’ve used template strings (back ticks) as I think they are best suited for this purpose and a lot clearer than concatenating.
You could use an alternative to your multi-dimensional array, a map possibly?
The answer anyway is to insert a class on the row you want highlighted.
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='UTF-8'>
<meta name='viewport' content='width=device-width, initial-scale=1.0'>
<title>Table</title>
<style>
table {
margin: 0 auto;
width: 80%;
border-collapse: collapse;
text-align: left;
}
th, td {
padding: 5px;
border: 1px solid black;
}
.highlight-row {
background-color: aquamarine;
}
</style>
</head>
<body>
<div class='container'></div>
<script>
window.addEventListener('DOMContentLoaded', function () {
const grades = [
['Grade 1', 6],
['Grade 2', 7],
['Grade 3', 8],
['Grade 4', 9],
['Grade 5', 10],
['Grade 6', 11]
];
function getAge ( year, month, day ) {
return new Date().getFullYear() - new Date(year, month, day).getFullYear()
}
function gradeTable ( grades, age ) {
const tableHead = `
<table>
<thead>
<tr class='highlight-row'>
<th>Grade</th>
<th>Age</th>
</tr>
</thead>
<tbody>
`;
const tableFoot = `
</tbody>
</table>
`;
const count = grades.length;
let tableBody = '';
for ( let i = 0; i < count; i += 1 ) {
let currGrade = grades[i][0];
let currAge = grades[i][1];
let highlight = (currAge === age) ? " class='highlight-row'" : '';
tableBody += `
<tr${highlight}>
<td>${currGrade}</td>
<td>${currAge}</td>
</tr>
`
}
return tableHead + tableBody + tableFoot;
}
document.querySelector('.container')
.insertAdjacentHTML(
'afterbegin',
gradeTable( grades, getAge( 2011, 4, 28 ) )
)
})
</script>
</body>
</html>
1 Like
system
Closed
July 20, 2020, 10:25am
3
This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.