How to shuffle a particular td every refresh the page? I have this Multiple Choice examination and I like to give a twist that every refresh the choices will shuffle, but the choices I have is inside table. I want to shuffle only the A,B, and C column.
Here's my code
var el
function togCell(col, asn) {
if (typeof event !== 'undefined')
el = event.srcElement
for (var i = 0; i < el.parentNode.cells.length; i++)
el.parentNode.cells[i].style.backgroundColor = '';
el.style.backgroundColor = col;
}
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;
}
<table>
<tr>
<th>Question</th>
<th>A</th>
<th>B</th>
<th>C</th>
</tr>
<tr>
<td>TESTING FIRST QUESTION</td>
<td onclick="togCell('#90ee90','AnsSelected_1')">FIRST Choices Correct</td>
<td onclick="togCell('#90ee90','AnsSelected_1')">FIRST Choices Wrong</td>
<td onclick="togCell('#90ee90','AnsSelected_1')">FIRST FIRST Choices Wrong</td>
</tr>
<tr>
<td>TESTING SECOND QUESTION</td>
<td onclick="togCell('#90ee90','AnsSelected_1')">SECOND Choices Wrong</td>
<td onclick="togCell('#90ee90','AnsSelected_1')">SECOND Choices Wrong</td>
<td onclick="togCell('#90ee90','AnsSelected_1')">SECOND Choices Correct</td>
</tr>
</table>
Expected output
Question | A | B | C |
---|---|---|---|
TESTING FIRST QUESTION | FIRST Choices Wrong | FIRST Choices Wrong | FIRST Choices Correct |
TESTING SECOND QUESTION | SECOND Choices Wrong | SECOND Choices Correct | SECOND Choices Wrong |
I just found out that why don't I put the whole td in variable then pass it into an array? since I can't put only the text content because I also have the id's that I need. This is what I've come up with
let tdA = `<td ansID="1" choicesID="1">FIRST Choices Correct</td>`;
let tdB = `<td ansID="1" choicesID="2">FIRST Choices Wrong</td>`;
let tdC = `<td ansID="1" choicesID="3">FIRST FIRST Choices Wrong</td>`;
var choicesArray = [tdA, tdB, tdC];
var shuffle = function (arr) {
for (var j, x, i = arr.length; i;j = parseInt(Math.random() * i),x = arr[--i],arr[i] = arr[j],arr[j] = x);
return arr;
}
shuffle(choicesArray);
$('#appendTr').append(
`<tr>` +
`<td>TESTING FIRST QUESTION</td>` +
`${choicesArray[0]}` +
`${choicesArray[1]}` +
`${choicesArray[2]}` +
`</tr>`
);
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;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<th>Question</th>
<th>A</th>
<th>B</th>
<th>C</th>
</tr>
<tbody id="appendTr"></tbody>
</table>