Random group with fixed match - javascript

I'm making a random group for an one-on-one debate, there are 16 people divided into 8 teams, and they will be assigned with 8 random topics as well as random sides(AFF & NEG).
Below is the part I used to generate random teams, the match will be held on am and pm so 8 per round.
For some reason we need two of them to be always in a match. I can't seem to do this in a logical way. I.E. Jerry Lin always debates with Sammy Singh, sides can change. Thanks in advance.
var team = [
"Sandra Tom*",
"Jerry Lin*",
"Josh Renaud*",
"Katie Bostian",
"Sammy Singh",
"Nader Shehayed*",
"Joseph Tu*",
"James Kim"
];
var text = "";
function shuffle(array) {
var currentIndex = array.length, temporaryValue, randomIndex;
// While there remain elements to shuffle...
while (0 !== currentIndex) {
// Pick a remaining element...
var randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
// And swap it with the current element.
var temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}
return array;
}
function shuffler() {
shuffle(team);
document.getElementById("player-0").innerHTML = team[0];
document.getElementById("player-1").innerHTML = team[1];
document.getElementById("player-2").innerHTML = team[2];
document.getElementById("player-3").innerHTML = team[3];
document.getElementById("player-4").innerHTML = team[4];
document.getElementById("player-5").innerHTML = team[5];
document.getElementById("player-6").innerHTML = team[6];
document.getElementById("player-7").innerHTML = team[7];
}
// var myInterval = setInterval(shuffler, 50);
// clearInterval(myInterval);
document.getElementById("random").addEventListener("click", shuffler);
window.addEventListener("keypress", checkKeyPressed, false);
function checkKeyPressed(e) {
if (e.charCode == "32") {
document.getElementById("random").addEventListener("click", shuffler);
}
}
body {
background-color: #232323;
}
#team {
box-shadow: 0px 0px 50px rgba(255,255,255,.25);
}
#team td {
height: 75px;
width: 300px;
text-align: center;
font-family: Helvetica, Arial, san-serif;
text-transform: uppercase;
font-weight: bold;
background-color: #000000;
color: #ffffff;
font-size: 24px;
padding: 0px;
}
#team .title {
height: 30px;
font-size: 16px;
}
#team .blue {
background-color: dodgerblue;
}
#team .red {
background-color: tomato;
}
#team .green {
background-color: olive;
}
#team .orange {
background-color: orange;
}
#team .grey {
background-color: #686868;
}
.fade {
opacity: 1;
transition: opacity .1s ease-in-out;
-moz-transition: opacity .1s ease-in-out;
-webkit-transition: opacity .1s ease-in-out;
}
<table align="center" id="team" cellpadding="0" cellspacing="0">
<tr>
<td colspan="2" class="title">
Team 1
</td>
</tr>
<tr>
<td id="player-0" class="blue"></td>
<td id="player-1" class="blue"></td>
</tr>
<tr>
<td colspan="2" class="title">
Team 2
</td>
</tr>
<tr>
<td id="player-2" class="red"></td>
<td id="player-3" class="red"></td>
</tr>
<tr>
<td colspan="2" class="title">
Team 3
</td>
</tr>
<tr>
<td id="player-4" class="green"></td>
<td id="player-5" class="green"></td>
</tr>
<tr>
<td colspan="2" class="title">
Team 4
</td>
</tr>
<tr>
<td id="player-6" class="orange"></td>
<td id="player-7" class="orange"></td>
</tr>
</table>
<table width="600" align="center">
<tr>
<td colspan="2" align="center">
<button id="random">RANDOM</button>
</td>
</tr>
</table>
Update:Snippet attached.
To clarify the question.
We want Jerry Lin always debates with Sammy Singh. 8 topics divided into am and pm, 16 people divided into 8 groups for those 8, all unique.

Define the two people who are always on the same team, then hack the shuffled team list. Check my solution below:
var team = [
"Sandra Tom*",
"Jerry Lin*",
"Josh Renaud*",
"Katie Bostian",
"Sammy Singh",
"Nader Shehayed*",
"Joseph Tu*",
"James Kim"
];
var text = "";
function shuffle(array) {
var currentIndex = array.length, temporaryValue, randomIndex;
// While there remain elements to shuffle...
while (0 !== currentIndex) {
// Pick a remaining element...
var randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
// And swap it with the current element.
var temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}
return array;
}
function hack(array, p1, p2){
var p1Index = array.indexOf(p1);
var p2Index = array.indexOf(p2);
if(p1Index % 2 === 0){
var temp = array[p1Index+1]
array[p1Index+1] = array[p2Index]
} else {
var temp = array[p1Index-1]
array[p1Index-1] = array[p2Index]
}
array[p2Index] = temp
return array
}
function shuffler() {
var shuffled = shuffle(team)
var hacked = hack(shuffled, "Jerry Lin*", "Sammy Singh")
var final = hacked
document.getElementById("player-0").innerHTML = final[0];
document.getElementById("player-1").innerHTML = final[1];
document.getElementById("player-2").innerHTML = final[2];
document.getElementById("player-3").innerHTML = final[3];
document.getElementById("player-4").innerHTML = final[4];
document.getElementById("player-5").innerHTML = final[5];
document.getElementById("player-6").innerHTML = final[6];
document.getElementById("player-7").innerHTML = final[7];
}
// var myInterval = setInterval(shuffler, 50);
// clearInterval(myInterval);
document.getElementById("random").addEventListener("click", shuffler);
window.addEventListener("keypress", checkKeyPressed, false);
function checkKeyPressed(e) {
if (e.charCode == "32") {
document.getElementById("random").addEventListener("click", shuffler);
}
}
body {
background-color: #232323;
}
#team {
box-shadow: 0px 0px 50px rgba(255,255,255,.25);
}
#team td {
height: 75px;
width: 300px;
text-align: center;
font-family: Helvetica, Arial, san-serif;
text-transform: uppercase;
font-weight: bold;
background-color: #000000;
color: #ffffff;
font-size: 24px;
padding: 0px;
}
#team .title {
height: 30px;
font-size: 16px;
}
#team .blue {
background-color: dodgerblue;
}
#team .red {
background-color: tomato;
}
#team .green {
background-color: olive;
}
#team .orange {
background-color: orange;
}
#team .grey {
background-color: #686868;
}
.fade {
opacity: 1;
transition: opacity .1s ease-in-out;
-moz-transition: opacity .1s ease-in-out;
-webkit-transition: opacity .1s ease-in-out;
}
<!DOCTYPE html>
<html lang="en" >
<head>
<meta charset="UTF-8">
<title>CodePen - Random Team Generator</title>
<!-- <link rel="stylesheet" href="./style.css"> -->
</head>
<body>
<!-- partial:index.partial.html -->
<body>
<table align="center" id="team" cellpadding="0" cellspacing="0">
<tr>
<td colspan="2" class="title">
Team 1
</td>
</tr>
<tr>
<td id="player-0" class="blue"></td>
<td id="player-1" class="blue"></td>
</tr>
<tr>
<td colspan="2" class="title">
Team 2
</td>
</tr>
<tr>
<td id="player-2" class="red"></td>
<td id="player-3" class="red"></td>
</tr>
<tr>
<td colspan="2" class="title">
Team 3
</td>
</tr>
<tr>
<td id="player-4" class="green"></td>
<td id="player-5" class="green"></td>
</tr>
<tr>
<td colspan="2" class="title">
Team 4
</td>
</tr>
<tr>
<td id="player-6" class="orange"></td>
<td id="player-7" class="orange"></td>
</tr>
</table>
<table width="600" align="center">
<tr>
<td colspan="2" align="center">
<button id="random">RANDOM</button>
</td>
</tr>
</table>
</body>
<!-- partial -->
<!-- <script src="./script.js"></script> -->
</body>
</html>

Based on your comments:
var team = [
["Sandra Tom*","Jerry Lin*"],
["Josh Renaud*","Katie Bostian"],
["Sammy Singh","Nader Shehayed*"],
["Joseph Tu*","James Kim"]
];
var text = "";
function shuffle(array) {
var currentIndex = array.length, temporaryValue, randomIndex;
// While there remain elements to shuffle...
while (0 !== currentIndex) {
// Pick a remaining element...
var randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
// And swap it with the current element.
var temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}
return array;
}
function shuffler() {
shuffle(team);
document.getElementById("player-0").innerHTML = team[0][0];
document.getElementById("player-1").innerHTML = team[0][1];
document.getElementById("player-2").innerHTML = team[1][0];
document.getElementById("player-3").innerHTML = team[1][1];
document.getElementById("player-4").innerHTML = team[2][0];
document.getElementById("player-5").innerHTML = team[2][1];
document.getElementById("player-6").innerHTML = team[3][0];
document.getElementById("player-7").innerHTML = team[3][1];
}

Related

Error or bug when switching CSS classes by JavaScript when dragging with mouse [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
Ok, here a simple code, which changes td class when you click on them:
const btn = document.getElementsByTagName("input")[0];
btn.addEventListener("click", function(event){
let cells = document.getElementsByTagName("td");
for (let i=0; i<cells.length; i++) {
cells[i].classList = ""
};
CounterCells();
})
const tabl = document.getElementsByTagName("table")[0];
tabl.addEventListener("click", function(event){
if (event.target.classList == ""){
event.target.classList.add("green");
console.log("Nothing to green");
} else if (event.target.classList.contains("white")){
event.target.classList.replace("white", "green");
console.log("White to green");
} else if (event.target.classList.contains("green")){
event.target.classList.replace("green", "red");
console.log("Green to red");
} else if (event.target.classList.contains("red")) {
event.target.classList.replace("red", "white");
console.log("Red to white");
}
CounterCells();
})
function CounterCells() {
let cells = document.getElementsByTagName("td");
let countWhites = 0;
let countGreens = 0;
let countReds = 0;
for (let i=0; i<cells.length; i++) {
if (cells[i].classList == "") {
countWhites++
}
if (cells[i].classList.contains("white")) {
countWhites++
}
if (cells[i].classList.contains("green")) {
countGreens++
}
if (cells[i].classList.contains("red")) {
countReds++
}
}
const p = document.getElementById("demo");
p.innerHTML = "Whites: "+countWhites+"<br> Greens: "+countGreens+"<br> Reds: "+countReds;
}
table {
border-collapse: collapse;
}
td {
border: 1px solid grey;
width: 2rem;
height: 2rem;
text-align: center;
cursor: pointer;
user-select: none;
}
.green {
background-color: green;
}
.red {
background-color: red;
}
.white {
background-color: white;
}
<input type="button" value="Reset">
<br>
<br>
<table>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
</tr>
<tr>
<td>4</td>
<td>5</td>
<td>6</td>
</tr>
<tr>
<td>7</td>
<td>8</td>
<td>9</td>
</tr>
</table>
<p id="demo"></p>
If you click it -- anything works fine, but now try to click on cell number one and drag mouse over cell number three and then release mouse button -- class will be assigned to tr not to last td number 3.
Why is that?
https://jsfiddle.net/foxnadir/Ls6p7j1z/3/
The problem in your code was that you were attaching the click event to the table element, when only one td can be clicked at a time.
I also changed the event from click to mousedown so that when the user drags from 1 to 3, 1 changes color, but if this behavior is not what you wanted, you can change it back.
Here is the working code:
const btn = document.getElementsByTagName("input")[0];
btn.addEventListener("click", function(event) {
let cells = document.getElementsByTagName("td");
for (let i = 0; i < cells.length; i++) {
cells[i].classList = ""
};
CounterCells();
})
let cells = document.getElementsByTagName("td");
for (i = 0; i < cells.length; i++) {
cells[i].addEventListener("mousedown", function(event) {
if (event.target.classList == "") {
event.target.classList.add("green");
console.log("Nothing to green");
} else if (event.target.classList.contains("white")) {
event.target.classList.replace("white", "green");
console.log("White to green");
} else if (event.target.classList.contains("green")) {
event.target.classList.replace("green", "red");
console.log("Green to red");
} else if (event.target.classList.contains("red")) {
event.target.classList.replace("red", "white");
console.log("Red to white");
}
CounterCells();
})
}
function CounterCells() {
let countWhites = 0;
let countGreens = 0;
let countReds = 0;
for (let i = 0; i < cells.length; i++) {
if (cells[i].classList == "") {
countWhites++
}
if (cells[i].classList.contains("white")) {
countWhites++
}
if (cells[i].classList.contains("green")) {
countGreens++
}
if (cells[i].classList.contains("red")) {
countReds++
}
}
const p = document.getElementById("demo");
p.innerHTML = "Whites: " + countWhites + "<br> Greens: " + countGreens + "<br> Reds: " + countReds;
}
table {
border-collapse: collapse;
}
td {
border: 1px solid grey;
width: 2rem;
height: 2rem;
text-align: center;
cursor: pointer;
user-select: none;
}
tr {
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
td {
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
.green {
background-color: green;
}
.red {
background-color: red;
}
.white {
background-color: white;
}
<input type="button" value="Reset">
<br>
<br>
<table>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
</tr>
<tr>
<td>4</td>
<td>5</td>
<td>6</td>
</tr>
<tr>
<td>7</td>
<td>8</td>
<td>9</td>
</tr>
</table>
<p id="demo"></p>

How to add a number dynamically with Javascript to the first cell

I'm learning Javascript and i'm stuck at the moment. When the user input their first name, last name, age and clicks on the button "add", 1 new row and 4 new cells are being added to the table with the value of the users input.
My question is: how do I get the first cell to be a number? Which in this case should be number 4. If the user adds another row with value it should become number 5. etc.
If somebody could point me in a direction or show me another way to do it, that would help. Thanks! (css added just for visuals)
function allID(id) {
return document.getElementById(id);
}
function allEvents() {
allID("voegdatatoe").onclick = function () {
voegToeGegevens();
};
}
allEvents();
function voegToeGegevens() {
var formulier = allID("invoerformulier");
var nieuweGegevens = [];
for (var i = 0; i < formulier.length; i++) {
nieuweGegevens[i] = formulier.elements[i].value;
}
var uitvoertabel = allID("uitvoertabel");
var nieuweRij = uitvoertabel.insertRow(-1);
for (i = 0; i < 4; i++) {
var NieuweCell = nieuweRij.insertCell(i);
NieuweCell.innerHTML = nieuweGegevens[i];
}
}
var row = document.getElementsByClassName("rownmr");
var i = 0;
for (i = 0; i < row.length; i++) {
row[i].innerHTML = i + 1;
}
table,
th,
td {
border-collapse: collapse;
border: 1px solid black;
}
th,
td {
padding: 5px;
}
th {
text-align: left;
background-color: #c95050;
color: white;
}
.uitvoertabel {
width: 60%;
}
.uitvoertabel tr:nth-child(even) {
background-color: #eee;
}
.uitvoertabel tbody tr td:first-child {
width: 30px;
}
.invoerform {
margin-top: 50px;
width: 30%;
}
.invoerform input,
label {
display: block;
}
.invoerform label {
margin-bottom: 5px;
margin-top: 10px;
}
#voegdatatoe {
margin-top: 30px;
}
input:focus {
border: 1px solid #d45757;
outline: none;
}
<table class="uitvoertabel" id="uitvoertabel">
<thead>
<tr>
<th></th>
<th>Voornaam</th>
<th>Achternaam</th>
<th>Leeftijd</th>
</tr>
</thead>
<tbody>
<tr>
<td class="rownmr"></td>
<td>Johan</td>
<td>cruijff</td>
<td>54</td>
</tr>
<tr>
<td class="rownmr"></td>
<td>Frans</td>
<td>Bauer</td>
<td>47</td>
</tr>
<tr>
<td class="rownmr"></td>
<td>Willem</td>
<td>van Oranje</td>
<td>80</td>
</tr>
</tbody>
</table>
<form action="" id="invoerformulier" class="invoerform">
<label>Voornaam:</label>
<input type="text" name="vnaam" id="voornaam">
<label>Achternaam:</label>
<input type="text" name="anaam" id="achternaam">
<label>Leeftijd:</label>
<input type="text" name="points" id="leeftijd">
</form>
<button id="voegdatatoe">Voeg toe</button>
There are a number of ways you could store this information, from a global variable (not recommended) to some local closure, or even localStorage. But you have the information in the DOM, so it might be simplest to use it.
One way to do this would be to scan the ids, find their maximum, and add one to it. This involves a few changes to your code. First, we would add some code to scan your id cells for the largest value:
var rows = document.getElementsByClassName("rownmr");
var highestId = Math.max(...([...rows].map(row => Number(row.textContent))))
Then we would start your content array with a new value one higher than that maximum:
var nieuweGegevens = [highestId + 1];
And your loop needs to take this into account by adding one to the index
for (var i = 0; i < formulier.length; i++) {
nieuweGegevens[i + 1] = formulier.elements[i].value;
}
Finally, we need to add the right class to that new cell so that on the next call, it will continue to work:
for (i = 0; i < 4; i++) {
var NieuweCell = nieuweRij.insertCell(i);
NieuweCell.innerHTML = nieuweGegevens[i];
if (i === 0) { /**** new ****/
NieuweCell.classList.add("rownmr") /**** new ****/
} /**** new ****/
}
You can see these changes inline in this snippet:
function allID(id) {
return document.getElementById(id);
}
function allEvents() {
allID("voegdatatoe").onclick = function () {
voegToeGegevens();
};
}
allEvents();
function voegToeGegevens() {
var formulier = allID("invoerformulier");
var rows = document.getElementsByClassName("rownmr");
var highestId = Math.max(...([...rows].map(row => Number(row.textContent))))
var nieuweGegevens = [highestId + 1];
for (var i = 0; i < formulier.length; i++) {
nieuweGegevens[i + 1] = formulier.elements[i].value;
}
var uitvoertabel = allID("uitvoertabel");
var nieuweRij = uitvoertabel.insertRow(-1);
for (i = 0; i < 4; i++) {
var NieuweCell = nieuweRij.insertCell(i);
NieuweCell.innerHTML = nieuweGegevens[i];
if (i === 0) {
NieuweCell.classList.add("rownmr")
}
}
}
var row = document.getElementsByClassName("rownmr");
var i = 0;
for (i = 0; i < row.length; i++) {
row[i].innerHTML = i + 1;
}
table,
th,
td {
border-collapse: collapse;
border: 1px solid black;
}
th,
td {
padding: 5px;
}
th {
text-align: left;
background-color: #c95050;
color: white;
}
.uitvoertabel {
width: 60%;
}
.uitvoertabel tr:nth-child(even) {
background-color: #eee;
}
.uitvoertabel tbody tr td:first-child {
width: 30px;
}
.invoerform {
margin-top: 50px;
width: 30%;
}
.invoerform input,
label {
display: block;
}
.invoerform label {
margin-bottom: 5px;
margin-top: 10px;
}
#voegdatatoe {
margin-top: 30px;
}
input:focus {
border: 1px solid #d45757;
outline: none;
}
<table class="uitvoertabel" id="uitvoertabel">
<thead>
<tr>
<th></th>
<th>Voornaam</th>
<th>Achternaam</th>
<th>Leeftijd</th>
</tr>
</thead>
<tbody>
<tr>
<td class="rownmr"></td>
<td>Johan</td>
<td>cruijff</td>
<td>54</td>
</tr>
<tr>
<td class="rownmr"></td>
<td>Frans</td>
<td>Bauer</td>
<td>47</td>
</tr>
<tr>
<td class="rownmr"></td>
<td>Willem</td>
<td>van Oranje</td>
<td>80</td>
</tr>
</tbody>
</table>
<form action="" id="invoerformulier" class="invoerform">
<label>Voornaam:</label>
<input type="text" name="vnaam" id="voornaam">
<label>Achternaam:</label>
<input type="text" name="anaam" id="achternaam">
<label>Leeftijd:</label>
<input type="text" name="points" id="leeftijd">
</form>
<button id="voegdatatoe">Voeg toe</button>
Note that this will continue to work on subsequent adds.
Add additional the length+1 param in the arrays of data
function allID(id) {
return document.getElementById(id);
}
function allEvents() {
allID("voegdatatoe").onclick = function () {
voegToeGegevens();
};
}
allEvents();
function voegToeGegevens() {
var row = document.getElementsByTagName("tr");
var formulier = allID("invoerformulier");
var nieuweGegevens = [];
nieuweGegevens.push(row.length) //length param for first column
for (var i = 0; i < formulier.length; i++) {
nieuweGegevens[i+1] = formulier.elements[i].value; //saving values from i=1
}
var uitvoertabel = allID("uitvoertabel");
var nieuweRij = uitvoertabel.insertRow(-1);
for (i = 0; i < 4; i++) {
var NieuweCell = nieuweRij.insertCell(i);
NieuweCell.innerHTML = nieuweGegevens[i];
}
}
var row = document.getElementsByClassName("rownmr");
var i = 0;
for (i = 0; i < row.length; i++) {
row[i].innerHTML = i + 1;
}
table,
th,
td {
border-collapse: collapse;
border: 1px solid black;
}
th,
td {
padding: 5px;
}
th {
text-align: left;
background-color: #c95050;
color: white;
}
.uitvoertabel {
width: 60%;
}
.uitvoertabel tr:nth-child(even) {
background-color: #eee;
}
.uitvoertabel tbody tr td:first-child {
width: 30px;
}
.invoerform {
margin-top: 50px;
width: 30%;
}
.invoerform input,
label {
display: block;
}
.invoerform label {
margin-bottom: 5px;
margin-top: 10px;
}
#voegdatatoe {
margin-top: 30px;
}
input:focus {
border: 1px solid #d45757;
outline: none;
}
<table class="uitvoertabel" id="uitvoertabel">
<thead>
<tr>
<th></th>
<th>Voornaam</th>
<th>Achternaam</th>
<th>Leeftijd</th>
</tr>
</thead>
<tbody>
<tr>
<td class="rownmr"></td>
<td>Johan</td>
<td>cruijff</td>
<td>54</td>
</tr>
<tr>
<td class="rownmr"></td>
<td>Frans</td>
<td>Bauer</td>
<td>47</td>
</tr>
<tr>
<td class="rownmr"></td>
<td>Willem</td>
<td>van Oranje</td>
<td>80</td>
</tr>
</tbody>
</table>
<form action="" id="invoerformulier" class="invoerform">
<label>Voornaam:</label>
<input type="text" name="vnaam" id="voornaam">
<label>Achternaam:</label>
<input type="text" name="anaam" id="achternaam">
<label>Leeftijd:</label>
<input type="text" name="points" id="leeftijd">
</form>
<button id="voegdatatoe">Voeg toe</button>
As I note that none of the answers made, does not seem to have the approval of Niekket (no validation for anybody),
and that the question asked is accompanied by a very rough example (the author admits to being bloked in his apprenticeship), using a lot of useless code...
So I propose this complete solution, which I hope is enlightening enough on the proper way of coding its problem ( imho ).
const
TableBody_uitvoertabel = document.querySelector('#uitvoertabel > tbody'),
form_invoerformulier = document.querySelector('#invoerformulier'),
in_voornaam = document.querySelector('#voornaam'),
in_achternaam = document.querySelector('#achternaam'),
in_leeftijd = document.querySelector('#leeftijd')
;
var
RowCount = 0; // global..
// place numbers in the first column
document.querySelectorAll('#uitvoertabel > tbody > tr td:first-child').forEach(
elmTR=>{ elmTR.textContent = ++RowCount }
);
form_invoerformulier.onsubmit = function(e) {
e.preventDefault();
let
column = 0,
row = TableBody_uitvoertabel.insertRow(-1)
;
row.insertCell(column++).textContent = ++RowCount;
row.insertCell(column++).textContent = in_voornaam.value;
row.insertCell(column++).textContent = in_achternaam.value;
row.insertCell(column++).textContent = in_leeftijd.value;
this.reset();
}
table, th, td {
border-collapse: collapse;
border: 1px solid black;
}
th, td { padding: 5px; }
th {
text-align: left;
background-color: #c95050;
color: white;
}
table.uitvoertabel { width: 60%; }
table.uitvoertabel tr:nth-child(even) {
background-color: #eee;
}
table.uitvoertabel tbody tr td:first-child {
width: 30px;
}
form.invoerform {
margin-top: 50px;
width: 30%;
}
form.invoerform input,
form.invoerform label {
display: block;
}
form.invoerform label {
margin-bottom: 5px;
margin-top: 10px;
}
form.invoerform button {
margin-top: 30px;
}
form.invoerform input:focus {
border-color: #d45757;
outline: none;
}
<table class="uitvoertabel" id="uitvoertabel">
<thead>
<tr>
<th></th><th>Voornaam</th><th>Achternaam</th><th>Leeftijd</th>
</tr>
</thead>
<tbody>
<tr>
<td></td><td>Johan</td><td>cruijff</td><td>54</td>
</tr>
<tr>
<td></td><td>Frans</td><td>Bauer</td><td>47</td>
</tr>
<tr>
<td></td><td>Willem</td><td>van Oranje</td><td>80</td>
</tr>
</tbody>
</table>
<form id="invoerformulier" class="invoerform">
<label>Voornaam:</label>
<input type="text" name="vnaam" id="voornaam">
<label>Achternaam:</label>
<input type="text" name="anaam" id="achternaam">
<label>Leeftijd:</label>
<input type="text" name="points" id="leeftijd">
<button type="submit">Voeg toe</button>
<button type="reset">Reset</button>
</form>
I think that the main issue is that you only manually set the rownmrs for the first time from line var row = document.getElementsByClassName("rownmr");
rather than every time you click on the "Voeg toe" button.
Ideally, for your hard coded numbers, they would be in the markup and the logic to grab the next rownmr to display and the adding of that cell happens on click.
html
<table class="uitvoertabel" id="uitvoertabel">
<thead>
<tr>
<th></th>
<th>Voornaam</th>
<th>Achternaam</th>
<th>Leeftijd</th>
</tr>
</thead>
<tbody>
<tr>
<td class="rownmr">1</td>
<td>Johan</td>
<td>cruijff</td>
<td>54</td>
</tr>
<tr>
<td class="rownmr">2</td>
<td>Frans</td>
<td>Bauer</td>
<td>47</td>
</tr>
<tr>
<td class="rownmr">3</td>
<td>Willem</td>
<td>van Oranje</td>
<td>80</td>
</tr>
</tbody>
</table>
<form action="" id="invoerformulier" class="invoerform">
<label>Voornaam:</label>
<input type="text" name="vnaam" id="voornaam">
<label>Achternaam:</label>
<input type="text" name="anaam" id="achternaam">
<label>Leeftijd:</label>
<input type="text" name="points" id="leeftijd">
</form>
<button id="voegdatatoe">Voeg toe</button>
js
function allID(id) {
return document.getElementById(id);
}
function allEvents() {
allID("voegdatatoe").onclick = function () {
voegToeGegevens();
};
}
allEvents();
function voegToeGegevens() {
var formulier = allID("invoerformulier");
var nieuweGegevens = [];
for (var i = 0; i < formulier.length; i++) {
nieuweGegevens[i] = formulier.elements[i].value;
}
var allRownmrs = document.getElementsByClassName('rownmr');
var lastRownmr = allRownmrs[allRownmrs.length - 1].innerHTML;
var nextRownmr = parseInt(lastRownmr) + 1;
var uitvoertabel = allID("uitvoertabel");
var nieuweRij = uitvoertabel.insertRow(-1);
for (i = 0; i < 4; i++) {
var NieuweCell = nieuweRij.insertCell(i)
// you probably can refactor here
if (i === 0) {
NieuweCell.innerHTML = nextRownmr
} else {
NieuweCell.innerHTML = nieuweGegevens[i - 1];
}
}
}

Compare items in an array against table items in JavaScript, Beginner

I created a really basic table with 20 numbers inside. I have then bodged together a system which creates an array of 20 numbers and shuffles it, there is then a button which displays one position of the array at a time.
What I want to do, which I haven't been able to figure out yet, is to use the number that has been generated to change to background color of that same number in the table. So if I drew the number 20 it would be marked on the table.
Please could you respond with JavaScript only as jQuery is still a little unknown at the moment.
// This bit shuffles an array
function shuffle(array) {
var i = array.length,
j = 0,
temp;
while (i--) {
j = Math.floor(Math.random() * (i+1));
// swap randomly chosen element with current element
temp = array[i];
array[i] = array[j];
array[j] = temp;
}
return array;
}
// Array input
var ranNums = shuffle([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]);
//This bit calls the position of the array
var f = 0; // the index of the current item to show
function nextNumber() {
document
.getElementById('test')
.innerHTML = ranNums[f++]; // get the item and increment
if (f == ranNums.length) f = 0; // reset to first element if you've reached the end
}
body {
background-color: white;
color: black;
font-size: 20px;
font-family: "Lucida Grande", Verdana,Arial, Helvetica, sans-serif;
}
h1, th {
font-family: Georgia, "Times New Roman",Times, serif;
}
h1 {
font-size: 28px;
}
table {
border-collapse: separate;
border-spacing: 30px;
float: left;
}
th, td {
padding: 30px;
border: 2px black solid;
text-align: center;
width: 20%;
}
h2 {
}
button {
}
#item20 {
background-color: red;
}
<h1>Bingo!</h1>
<h2 id="test"></h2>
<table>
<tr>
<td id="item1"<h1>1</h1></td>
<td id="item2"<h1>2</h1></td>
<td id="item3"<h1>3</h1></td>
<td id="item4"<h1>4</h1></td>
<td id="item5"<h1>5</h1></td>
</tr>
<tr>
<td id="item6"<h1>6</h1></td>
<td id="item7"<h1>7</h1></td>
<td id="item8"<h1>8</h1></td>
<td id="item9"<h1>9</h1></td>
<td id="item10"<h1>10</h1></td>
</tr>
<tr>
<td id="item11"<h1>11</h1></td>
<td id="item12"<h1>12</h1></td>
<td id="item13"<h1>13</h1></td>
<td id="item14"<h1>14</h1></td>
<td id="item15"<h1>15</h1></td>
</tr>
<tr>
<td id="item16"<h1>16</h1></td>
<td id="item17"<h1>17</h1></td>
<td id="item18"<h1>18</h1></td>
<td id="item19"<h1>19</h1></td>
<td id="item20"<h1>20</h1></td>
</tr>
</table>
<button onclick="nextNumber()">Next Number</button>
Change your nextNumber method to also highlight the new random number selected
function nextNumber() {
var number = ranNums[f];
f++;
document.getElementById('test').innerHTML = number;
document.getElementById("item" + number).style.backgroundColor = "red";
if (f == ranNums.length) f = 0; // reset to first element if you've reached the end
}
Demo
// This bit shuffles an array
function shuffle(array) {
var i = array.length,
j = 0,
temp;
while (i--) {
j = Math.floor(Math.random() * (i + 1));
// swap randomly chosen element with current element
temp = array[i];
array[i] = array[j];
array[j] = temp;
}
return array;
}
// Array input
var ranNums = shuffle([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]);
//This bit calls the position of the array
var f = 0; // the index of the current item to show
function nextNumber() {
var number = ranNums[f];
f++;
document.getElementById('test').innerHTML = number;
document.getElementById("item" + number).style.backgroundColor = "red";
if (f == ranNums.length) f = 0; // reset to first element if you've reached the end
}
body {
background-color: white;
color: black;
font-size: 20px;
font-family: "Lucida Grande", Verdana, Arial, Helvetica, sans-serif;
}
h1,
th {
font-family: Georgia, "Times New Roman", Times, serif;
}
h1 {
font-size: 28px;
}
table {
border-collapse: separate;
border-spacing: 30px;
float: left;
}
th,
td {
padding: 30px;
border: 2px black solid;
text-align: center;
width: 20%;
}
h2 {}
button {}
#item20 {
background-color: red;
}
<h1>Bingo!</h1>
<h2 id="test"></h2>
<table>
<tr>
<td id="item1" <h1>1</h1>
</td>
<td id="item2" <h1>2</h1>
</td>
<td id="item3" <h1>3</h1>
</td>
<td id="item4" <h1>4</h1>
</td>
<td id="item5" <h1>5</h1>
</td>
</tr>
<tr>
<td id="item6" <h1>6</h1>
</td>
<td id="item7" <h1>7</h1>
</td>
<td id="item8" <h1>8</h1>
</td>
<td id="item9" <h1>9</h1>
</td>
<td id="item10" <h1>10</h1>
</td>
</tr>
<tr>
<td id="item11" <h1>11</h1>
</td>
<td id="item12" <h1>12</h1>
</td>
<td id="item13" <h1>13</h1>
</td>
<td id="item14" <h1>14</h1>
</td>
<td id="item15" <h1>15</h1>
</td>
</tr>
<tr>
<td id="item16" <h1>16</h1>
</td>
<td id="item17" <h1>17</h1>
</td>
<td id="item18" <h1>18</h1>
</td>
<td id="item19" <h1>19</h1>
</td>
<td id="item20" <h1>20</h1>
</td>
</tr>
</table>
<button onclick="nextNumber()">Next Number</button>
You could clean this up a bit, but this one uses a red class. The key is to target the box using document.getElementById("item" + randNum).className = "red";
I have added a resetNumbers() function and button to reset your classes. This is to display the reason why I chose to use a class. Originally I had it resetting after every button click, but if this is BINGO, that probably is not desired. I commented out where I was doing this, but you can still reset.
I prefer this to setting the background colour, as this is controlled through a css class instead, which is easier to manage.
// This bit shuffles an array
function shuffle(array) {
var i = array.length,
j = 0,
temp;
while (i--) {
j = Math.floor(Math.random() * (i+1));
// swap randomly chosen element with current element
temp = array[i];
array[i] = array[j];
array[j] = temp;
}
return array;
}
// Array input
var ranNums = shuffle([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]);
//This bit calls the position of the array
var f = 0; // the index of the current item to show
function nextNumber() {
var randNum = ranNums[f++];
document.getElementById('test').innerHTML = randNum; // get the item and increment
if (f == ranNums.length) f = 0; // reset to first element if you've reached the end
//resetNumbers();//uncomment if you do not want to reset - or remove if you never want this here
document.getElementById("item" + randNum).className = "red";
}
function resetNumbers() {
for (var i = 0; i < ranNums.length; i++) {
document.getElementById("item" + ranNums[i]).className = "";
}
}
body {
background-color: white;
color: black;
font-size: 20px;
font-family: "Lucida Grande", Verdana,Arial, Helvetica, sans-serif;
}
h1, th {
font-family: Georgia, "Times New Roman",Times, serif;
}
h1 {
font-size: 28px;
}
table {
border-collapse: separate;
border-spacing: 30px;
float: left;
}
th, td {
padding: 30px;
border: 2px black solid;
text-align: center;
width: 20%;
}
.red {
background-color: red;
}
<h1>Bingo!</h1>
<h2 id="test"></h2>
<table>
<tr>
<td id="item1"<h1>1</h1></td>
<td id="item2"<h1>2</h1></td>
<td id="item3"<h1>3</h1></td>
<td id="item4"<h1>4</h1></td>
<td id="item5"<h1>5</h1></td>
</tr>
<tr>
<td id="item6"<h1>6</h1></td>
<td id="item7"<h1>7</h1></td>
<td id="item8"<h1>8</h1></td>
<td id="item9"<h1>9</h1></td>
<td id="item10"<h1>10</h1></td>
</tr>
<tr>
<td id="item11"<h1>11</h1></td>
<td id="item12"<h1>12</h1></td>
<td id="item13"<h1>13</h1></td>
<td id="item14"<h1>14</h1></td>
<td id="item15"<h1>15</h1></td>
</tr>
<tr>
<td id="item16"<h1>16</h1></td>
<td id="item17"<h1>17</h1></td>
<td id="item18"<h1>18</h1></td>
<td id="item19"<h1>19</h1></td>
<td id="item20"<h1>20</h1></td>
</tr>
</table>
<button onclick="nextNumber()">Next Number</button>
<button onclick="resetNumbers()">Reset Numbers</button>

How do I split a table column into new columns from the nth delimiter onwards

I managed to create some code that splits, at the slash delimiter, the third column into new columns.
What I did not manage to do is make it split from the nth (i.e. 2nd) occurrence onwards.
I could not find a similar question on the internet, that's why I post i here.
The desired outcome should be as follows:
function split() {
var delimiter = "/";
var arr = [];
var highest = 0;
var columnIndex = "";
$('#tbl td:nth-child(3)').each(function() {
ColumnIndex = $(this).index();
var string = $(this).text();
var array = string.split(delimiter);
var nbrCharacter = (string.split(delimiter).length - 1) //COUNT OCCURENCES OF CHARACTER
var temp = (nbrCharacter > highest) ? highest++ : highest = highest;
arr.push(string.split(delimiter));
});
for (i = 0; i < highest; i++) { //ADD EMPTY COLUMNS
$('#tbl').find('tr').each(function() {
$(this).find('td').eq(ColumnIndex).after('<td></td>');
});
}
for (i = 0; i < arr.length; i++) { //POPULATE CELLS FROM ARRAY
var columnTracker = ColumnIndex
for (j = 0; j < arr[i].length; j++) {
$('#tbl').find('tr:eq(' + (i + 1) + ')').find('td:eq(' + columnTracker + ')').html(arr[i][j]);
columnTracker++
}
}
}
th {
height: 15px;
min-width: 30px;
border: 1px solid black;
font-size: 12px;
font-family: Courier, monospace;
padding: 2px 5px 2px 5px;
}
td {
height: 15px;
min-width: 30px;
border: 1px solid black;
font-size: 12px;
font-family: Courier, monospace;
padding: 2px 5px 2px 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" onclick="split()">Split</button>
<br>
<br>
<table id="tbl">
<thead>
<tr class="tbl-header">
<th>1</th>
<th>2</th>
<th>3</th>
<th>4</th>
</tr>
</thead>
<tbody>
<tr>
<td>A/B/C</td>
<td>B/C</td>
<td>C</td>
<td></td>
</tr>
<tr>
<td>A/B</td>
<td>B/C</td>
<td></td>
<td>D/E</td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>A/B/C/D</td>
<td></td>
<td>C/D/E</td>
<td>D/E/F</td>
</tr>
<tr>
<td></td>
<td>B/C/D</td>
<td>C/D</td>
<td>D/E/F/G</td>
</tr>
<tr>
<td>A/B/C</td>
<td>B/C/D/E</td>
<td>C/D/E/F</td>
<td></td>
</tr>
</tbody>
</table>

one js function call in multiple elements, jsp

I have a table with many rows. In each row I have to show a countdown timer with given value.
This is my js function in jsp.
<script>
function start(initial_time) {
var initialTime = initial_time.value;
tick();
setInterval(function () {
tick();
if (initialTime < -1) reset();
if (initialTime < 6) paint("red")
}, 1000)
function tick() {
document.getElementById("time").innerHTML = initialTime.toString();
--initialTime;
}
function reset() {
initialTime = 30;
tick();
paint("black");
}
function paint(color) {
document.getElementById("time").style.color = color;
}
}
This is my table row in the same jsp page
<table style="width: 100%; height: 100%; table-layout: fixed;" align="center">
<tbody >
<c:forEach items="${data.getCards()}" var="card">
<tr>
<td style="table-layout: fixed; vertical-align: middle; font-size: 30px; text-align: left; width: 100%; background-color: #78909C;"
colspan="4">${card.getLocationName()}</td>
</tr>
<tr>
<td style="vertical-align: middle; font-size: 24px; text-align: left; width: 70%; background-color: #b0bec5;"
colspan="3">Time left for next density check
</td>
<td style="vertical-align: middle; font-size: 22px; text-align: left; width: 30%; background-color: #b0bec5;" colspan="1">
<div id="time" onload="start(${card.getDefaultServerDensityValue()})"></div> <input hidden="hidden" id="density" value="${card.getDefaultServerDensityValue()}"/>
</td>
</tr>
Seems ok but timers in rows does'n shown up, does anybody knows why?
Your HTML structure Should be in JSP.
<table id="mytable" style="width: 100%; height: 100%; table-layout: fixed;" align="center">
<tbody >
<c:forEach items="${data.getCards()}" var="card">
<tr>
<td style="table-layout: fixed; vertical-align: middle; font-size: 30px; text-align: left; width: 100%; background-color: #78909C;"
colspan="4">${card.getLocationName()}</td>
</tr>
<tr>
<td style="vertical-align: middle; font-size: 24px; text-align: left; width: 70%; background-color: #b0bec5;"
colspan="3">Time left for next density check
</td>
<td style="vertical-align: middle; font-size: 22px; text-align: left; width: 30%; background-color: #b0bec5;" colspan="1">
<div data-timer="${card.getDefaultServerDensityValue()}"></div> <input hidden="hidden" id="density" value="${card.getDefaultServerDensityValue()}"/>
</td>
</tr>
</tbody>
</table>
You Jquery code Should be
<script>
function start(initial_time, ele) {
var initialTime = parseInt(initial_time);
tick();
setInterval(function () {
tick();
if (initialTime < -1) reset();
if (initialTime < 6) paint("red")
}, 1000)
function tick() {
ele.innerHTML = initialTime.toString();
--initialTime;
}
function reset() {
initialTime = 30;
tick();
paint("black");
}
function paint(color) {
ele.style.color = color;
}
}
$(document).ready(function(){
$("#my_table tbody td[data-timer]").each(function(){
start($(this).data("timer"),$(this)[0]);
});
})
This is how finally it was got done.
JQuery part
<script>
function start(initial_time, ele) {
var initialTime = parseInt(initial_time);
tick();
setInterval(function () {
tick();
if (initialTime < -1) reset();
if (initialTime < 6) paint("red")
}, 1000)
function tick() {
ele.innerHTML = initialTime.toString();
--initialTime;
}
function reset() {
initialTime = initial_time;
tick();
paint("red");
}
function paint(color) {
ele.style.color = color;
}
}
(function() {
$("#mytable").find("div[data-timer]").each(function(){
start($(this).data("timer"),$(this)[0]);
});
})();
For those who is as new to JQuery as I am, you need to incl;ude in your JSP page Jquery libs this way
<script src="http://code.jquery.com/jquery-1.10.2.js"
type="text/javascript"></script>`
Include after <head> tag
In JSP your timer element will look like
<div data-timer="${card.getDefaultServerDensityValue()}"></div>
You can use any other element instead of <div> .
Also make sure to give an id to your table
<table id="mytable" style="width: 100%; height: 100%; table-layout: fixed;" align="center">
And make sure that id of table matches with $("#mytable") in javascript.
Result is
Where red numbers are counting down.

Categories

Resources