I am new to Javascript and am having problems with looping my function.
I am trying to loop through a table and convert the numbers in the second column to a rating in the third column. I have defined a function to convert the numerical rating into text ("Good", "Bad", ...) which I then want to use in my loop. For some reason, the conversion works for the first row but stops at the second.
I couldn't find a answer on here, could anyone help? Thanks
function convert(number) {
if (number == 1) {
return convert = "Bad";
} else if (number == 2) {
return convert = "Satisfactory";
} else if (number == 3) {
return convert = "Moderate Good";
} else if (number == 4) {
return convert = "Good";
} else {
return convert = "Excellent";
}
}
var table = document.getElementById("results");
var rows = table.rows;
var rowcount = rows.length;
console.log(rowcount);
var num = [];
var txt = [];
for(var i = 1; i < rowcount ; i++) {
num[i] = parseInt(table.rows[i].cells.item(1).innerHTML);
txt[i] = convert( num[i] );
table.rows[i].cells.item(2).innerHTML = txt[i];
}
<table id="results">
<thead>
<tr>
<th>Question number</th>
<th>Assessment value</th>
<th>Output text</th>
</tr>
</thead>
<tr>
<td>Q1</td>
<td>4</td>
<td></td>
</tr>
<tr>
<td>Q2</td>
<td>4</td>
<td></td>
</tr>
<tr>
<td>Q3</td>
<td>3</td>
<td></td>
</tr>
<tr>
<td>Q4</td>
<td>2</td>
<td></td>
</tr>
<tr>
<td>Q5</td>
<td>5</td>
<td></td>
</tr>
</table>