changing background using css and javascript - javascript

I am stuck in a place and I would like your ideas on how to solve this issue.
var vaction = "{{vaction}}";
if(vaction === "Driving")
document.getElementByClassName("cover").style.backgroundImage = url(https://media.nature.com/lw800/magazine-assets/d41586-018-04158-5/d41586-018-04158-5_15590100.gif);
document.getElementByClassName("table1, table2").style.backgroundColor = 'lime';
else if(vaction === "Sounding The Alarm")
document.getElementByClassName("cover").style.backgroundImage= url(https://upload.wikimedia.org/wikipedia/commons/e/eb/Blinking_warning.gif);
document.getElementByClassName("table1, table2").style.backgroundColor = 'orange';
else if(vaction === "Pulling over")
document.getElementByClassName("cover").style.backgroundImage = url(https://browsifyapp.com/wp-content/uploads/2018/10/model-3-gif-yeah.gif);
document.getElementByClassName("table1, table2").style.backgroundColor = 'red';
</script>
<style>
table.table2, table.table1 {
width: 190.5px;
height: 50px;
text-align: left;
border-collapse: collapse;
}
table.table1, td, th, table.table2 td, th {
border: 1px solid black;
}
html , body {
height: 100%;
margin: 0;
padding: 0;
}
div.cover {
background-repeat: no-repeat;
background-size: cover;
background-position: center;
width: 100%;
height: 100%;
}
</style>
<div class="cover">
<div>
<table class="table1">
<thead><tr><th>Focus</th><th>State</th><th>Alert Level</th></tr></thead>
<tr><td>Eyes</td><td> {{estate}} </td><td> {{elevel}} </td></tr>
<tr><td>Head</td><td> {{hstate}} </td><td> {{hlevel}} </td></tr>
<tr><td>Body</td><td> {{bstate}} </td><td> {{blevel}} </td></tr>
<tr><td>Vehicle</td><td> {{vstate}} </td><td> {{vlevel}} </td></tr>
</table>
<table class="table2">
<thead><tr><th>Current action</th></tr></thead>
<tr><td> {{vaction}} </td></tr>
</table>
</div>
</div>
The idea behind this is that I want to change the background gif and table1, table2 background color according to the variable answer. These inputs are gathered from flaks. I just have no idea how to style this.

if(!NodeList.prototype.forEach) // document.querySelectorAll('...').forEach not supported in IE for support add this :D
NodeList.prototype.forEach = function(that){
for(var i = 0; i < this.length; i++)
that(this[i]);
};
function change(gif_url, tb1_tb2_color) {
document.querySelector("div.cover").style.backgroundImage = gif_url;
document.querySelectorAll(".table1, .table2").forEach(function(tb) {
tb.style.background = tb1_tb2_color;
});
}
switch("{{vaction}}") {
case "Driving":
change("url(https://media.nature.com/lw800/magazine-assets/d41586-018-04158-5/d41586-018-04158-5_15590100.gif)", "lime");
break;
case "Sounding The Alarm":
change("url(https://upload.wikimedia.org/wikipedia/commons/e/eb/Blinking_warning.gif)", "orange");
break;
case "Pulling over":
change("url(https://browsifyapp.com/wp-content/uploads/2018/10/model-3-gif-yeah.gif)", "red");
break;
}

Related

Local Storage with multiple contentEditable

I have currently figured out a way to store value of 6am plan in a content editable box in my local storage key
item 2
How do I make this happen for all the other hours like 1
work plan for every hour of the day 6 am - 11pm
storing input in one key
using this code snippet below
javascript -
var content = document.getElementById('content'),
address = document.getElementById('address'),
saveButton = document.getElementById('save'),
loadButton = document.getElementById('load'),
clearButton = document.getElementById('clear'),
resetButton = document.getElementById('reset');
var localStore = {
saveLocalStorage: function() {
localStorage.setItem('item', content.innerHTML);
},
loadLocalStorage: function() {
var contentStored = localStorage.getItem('item');
if ( contentStored ) {
content.innerHTML = contentStored;
}
},
clearLocalStorage: function() {
localStorage.removeItem('item');
}
};
saveButton.addEventListener('click', function() {
localStore.saveLocalStorage();
}, false);
<r class="notion-table-row">
<td
style="color: inherit; fill: inherit; border: 1px solid gb(233, 233, 231); position: relative; vertical-align: top; min-width: 122px; max-width: 122px; min-height: 32px;">
<div class="notion-table-cell">
<div class="notion-table-cell-text"
spellcheck="true" placeholder=" "
data-content-editable-leaf="true"
style="max-width: 100%; width: 100%; white-space: pre-wrap; word-break: break-word; caret-colour: gb(55, 53, 47); padding: 7px 9px; background-colour: transparent; font-size: 14px; line-height: 20px;"
content editable="false">11 PM</div>
</div>
</td>
<td
style="color: inherit; fill: inherit; border: 1px solid gb(233, 233, 231); position: relative; vertical-align: top; min-width: 200px; max-width: 200px; min-height: 32px;">
<div class="notion-table-cell">
<div class="notion-table-cell-text"
spellcheck="true" placeholder=" "
data-content-editable-leaf="true"
style="max-width: 100%; width: 100%; white-space: pre-wrap; word-break: break-word; caret-colour: gb (55, 53, 47); padding: 7px 9px; background - colour: transparent; font-size: 14px; line-height: 20px;"
<section id="11pm_input" content editable="true"></div>
Store all of the data in an array. Keep in mind, localStorage stores only strings so anything not a string (ex. array, object, number, etc.), must be converted into a string when saved to localStorage:
localStorage.setItem("String", JSON.stringify([...Array]))
and when it is retrieved from localStorge it needs to be parsed into it's original type:
const data = JSON.parse(localStorage.getItem("String"));
In the example below, the data is gathered from all .cell which comprise of the following HTML elements from the table head and body (in ex. 4 x time, 6 x data):
<time class='cell' datetime="23:00">11 PM</time>
<data class='cell' value="0ne Zer0">Zer0 0ne</data>
time.datetime = "23:00";
time.textContent = "11 PM";
data.value = "0ne Zer0";
data.textContent = "Zer0 0ne";
lStorage = [
["23:00", "11 PM"],
["0ne Zer0", "Zer0 0ne"],
["00:00", "12 AM"],
...[N, N]
];
The event handler manageData(event) delegated all click events triggered on the table head, body, and foot.
Variables:
key is whatever the user typed in .input, the value will be assigned to data being saved to localStorage.
data is declared for data coming from and to localStorage.
cells is an array of all time.cell and data.cell tags within the table head and body.
node is determined by event.target property which always refers to the tag the user actually clicked. This reference will be delegated to react according to the .matches() method and a series of flow control statements (if, if else, and else).
The process for loading data from localStorage involves loadData(key) and iteration of the array of arrays saved in localStorage and the array of .cells:
if (node.matches('.load')) {...
...
data = loadData(key);
cells.forEach((n, i) => {
n.textContent = data[i][1];
if (n.matches('time')) {
n.datetime = data[i][0];
} else {
n.value = data[i][0];
}
});
The rest of the code is of simular fashion -- here's a brief description of what it can do:
Load data from key in localStorage and popualte a <table> with it.
Save data from a <table> to a key in localStorage.
Reset data the user typed in the fields (if given a selector, it can reset it as well).
Clear data by key and all data in <table> (including static data).
All .cells are editable (including headers). Double click any .cell within the table head or body to toggle it in/out of edit mode.
Due to SO security policy, WebStorage API will not function, go to: Plunker
The link doesn't work for me when clicked but
I managed to use the url by copy & paste
to the address bar:
https://run.plnkr.co/preview/ckz3pfkfe0007386nlancnzqk/
If the links above don't work, you can copy & paste the code in the Snippet with a text editor and save the file with a *.html extension.
<!DOCTYPE html>
<html lang="en">
<head>
<title></title>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<style>
:root {
font: 1ch/1.5 'Segoe UI';
}
body {
font-size: 2ch;
}
table {
table-layout: fixed;
width: 70vw;
margin: 20px auto;
}
th {
width: 50%;
font-size: 2.25rem;
}
td {
vertical-align: center;
}
.box {
display: flex;
flex-flow: column nowrap;
justify-content: center;
align-items: center;
min-height: 32px;
padding: 8px 8px 5px;
}
.cell {
display: block;
max-width: 100%;
width: 100%;
min-height: 25px;
white-space: pre-wrap;
word-break: break-word;
font-size: 2rem;
border: 2px solid #000;
background: transparent;
text-align: center;
}
.head {
width: 97.5%;
border-color: transparent;
}
.edit {
border-color: blue;
}
button {
display: block;
font: inherit;
font-size: 2rem;
background: transparent;
border-radius: 6px;
cursor: pointer;
}
button:hover {
border-color: blue;
color: blue;
background: #ddd;
}
.ctrl {
position: relative;
flex-flow: row nowrap;
justify-content: space-between;
min-width: 92%;
height: 30px;
margin-top: 40px;
}
.input {
position: absolute;
top: -40px;
left: -0.5vw;
width: 99%;
height: 25px;
}
.noKey {
color: tomato;
font-weight: 900;
border-color: tomato;
}
.noKey::before {
content: 'Enter the key to data';
}
.done {
color: blue;
border-color: blue;
}
.done::before {
content: 'Data is saved under key: "';
}
.done::after {
content: '"';
}
</style>
</head>
<body>
<main>
<section>
<table>
<thead>
<tr>
<th>
<data class="cell head" value="Hour">Hour</data>
</th>
<th>
<data class="cell head" value="Employee">Employee</data>
</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<fieldset class="box">
<time class="cell">8 PM</time>
</fieldset>
</td>
<td>
<fieldset class="box">
<data class="cell edit" contenteditable></data>
</fieldset>
</td>
</tr>
<tr>
<td>
<fieldset class="box">
<time class="cell">9 PM</time>
</fieldset>
</td>
<td>
<fieldset class="box">
<data class="cell edit" contenteditable></data>
</fieldset>
</td>
</tr>
<tr>
<td>
<fieldset class="box">
<time class="cell">10 PM</time>
</fieldset>
</td>
<td>
<fieldset class="box">
<data class="cell edit" contenteditable></data>
</fieldset>
</td>
</tr>
<tr>
<td>
<fieldset class="box">
<time class="cell">11 PM</time>
</fieldset>
</td>
<td>
<fieldset class="box">
<data class="cell edit" contenteditable></data>
</fieldset>
</td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan="2">
<fieldset class="ctrl box">
<data class="cell input edit" contenteditable></data>
<button class="load" title="Load data">
Load</button>
<button class="save" title="Save data">
Save</button>
<button class="reset" title="Reset fields">
Reset</button>
<button class="clear" title="Clear saved data and Reset fields">
Clear</button>
</fieldset>
</td>
</tr>
</tfoot>
</table>
</section>
</main>
<script>
const tab = document.querySelector('table');
const hdr = tab.tHead;
const mid = tab.tBodies[0];
const ftr = tab.tFoot;
const cls = ['noKey', 'done'];
const inp = document.querySelector('.input');
const formatTime = time => {
const T = time.split(' ');
return T[1] === 'PM' ? `${+T[0]+12}:00` : `${T[0]}:00`;
};
const lastFirst = name => name.split(' ').reverse().join(', ');
const loadData = key => JSON.parse(localStorage.getItem(key));
const saveData = (key, data) => localStorage.setItem(key, JSON.stringify(data));
const resetData = selector => {
let nodes = selector === undefined ? '.edit' : selector;
[...document.querySelectorAll(nodes)].forEach(n => {
n.textContent = '';
if (n.matches('time')) {
n.datetime = '';
} else {
n.value = '';
}
});
inp.classList.remove(...cls);
};
const clearData = key => {
resetData('.cell');
inp.classList.remove(...cls);
localStorage.removeItem(key);
};
const manageData = e => {
let key = inp.textContent;
let data;
const cells = [...document.querySelectorAll('.cell')];
const node = e.target;
if (node.matches('.load')) {
if (key.length < 1) {
inp.classList.add('noKey');
} else {
data = loadData(key);
cells.forEach((n, i) => {
n.textContent = data[i][1];
if (n.matches('time')) {
n.datetime = data[i][0];
} else {
n.value = data[i][0];
}
});
}
} else if (node.matches('.save')) {
if (key.length < 1) {
inp.classList.add('noKey');
} else {
data = cells.flatMap(n => {
if (n.matches('time')) {
n.datetime = formatTime(n.textContent);
return [
[n.datetime, n.textContent]
];
} else {
n.value = lastFirst(n.textContent);
return [
[n.value, n.textContent]
];
}
});
inp.classList.add('done');
saveData(key, data);
}
} else if (node.matches('.reset')) {
resetData();
} else if (node.matches('.clear')) {
if (key.length < 1) {
inp.classList.add('noKey');
} else {
clearData(key);
}
} else if (node.matches('.input')) {
node.textContent = '';
node.classList.remove(...cls);
} else {
return;
}
};
ftr.onclick = manageData;
const toggleEdit = e => {
const node = e.target;
if (node.matches('.cell')) {
node.classList.toggle('edit');
node.toggleAttribute('contenteditable');
}
};
hdr.ondblclick = toggleEdit;
mid.ondblclick = toggleEdit;
</script>
</body>
</html>

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];
}
}
}

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.

How can I search in the js array?

I'm trying to suggest the name of people when user inputs # in the textarea. Here is what I have done so far:
var Names = $('td').map(function() { return $(this).text(); }).get();
function SuggestPeople() {
var $textarea = $('.TxtArea');
var textarea = $textarea[0];
var sel = $textarea.getSelection();
var val = textarea.value;
var pos = sel.start;
if(val.substr(pos-1,1) == '#'){
for (var i = 0; i < Names.length; i++) {
Names[i] = "<span>" + Names[i] + "</span>";
}
$('.SuggestPeople').html(Names);
} else {
$('.SuggestPeople').html('');
}
}
$('.TxtArea').on('keydown click', function(e) {
// e.preventDefault();
SuggestPeople();
});
table{
display:none;
}
div{
background-color:#eee;
min-height: 20px;
width: 200px;
padding-top:5px;
margin-bottom: 3px;
}
div > span{
border: 1px solid gray;
margin: 0 3px;
}
textarea{
width: 195px;
height: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://rangyinputs.googlecode.com/svn/trunk/rangyinputs_jquery.min.js"></script>
<table>
<tr>
<td>Jack</td>
<td>Peter</td>
<td>Barmar</td>
</tr>
</table>
<div class="SuggestPeople"></div>
<textarea class="TxtArea"></textarea>
In the code above, it suggests all names (which are exist in the array) to user. But actually I need to improve it and just suggest those names which are near to what user writes after #. How can I do that? I want exactly something like stackoverflow.
Here's a solution that should work for you:
// polyfills for older browsers
if (!String.prototype.startsWith) {
String.prototype.startsWith = function(searchString, position){
position = position || 0;
return this.substr(position, searchString.length) === searchString;
};
}
// code
var Names = $('td').map(function () {
return $(this).text();
}).get();
function SuggestPeople(e) {
var val = e.target.value,
suggest = document.getElementById('SuggestPeople');
if (val.substr(- 2).startsWith('#')) {
suggest.innerHTML = '<span>' + Names.map(function (v) {
var end = val.substr(- 1).toLowerCase();
if (v.startsWith(end) || v.startsWith(end.toUpperCase())) {
return v;
}
}).filter(function (v) {
return v
}).join('</span><span>') + '</span>'
} else {
suggest.innerHTML = '';
}
}
$('.TxtArea').on('keyup', function (e) {
// e.preventDefault();
SuggestPeople(e);
});
table{
display:none;
}
div{
background-color:#eee;
min-height: 20px;
width: 200px;
padding-top:5px;
margin-bottom: 3px;
}
div > span{
border: 1px solid gray;
margin: 0 3px;
}
textarea{
width: 195px;
height: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://rangyinputs.googlecode.com/svn/trunk/rangyinputs_jquery.min.js"></script>
<table>
<tr>
<td>Jack</td>
<td>Peter</td>
<td>Barmar</td>
</tr>
</table>
<div id="SuggestPeople"></div>
<textarea class="TxtArea"></textarea>
Please note that String.prototype.startsWith() doesn't work in IE and older browsers, but you can find a polyfill here: https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith

Move div to certain table cell according to random number [duplicate]

This question already has answers here:
How to move an element into another element
(16 answers)
Closed 7 years ago.
I am new at JavaScript. I am trying to make Snakes and Ladders game with native JavaScript code as much as possible. My problem is that I can not move players from their initial position according to the random number generated when pressing on dice image. Can anyone help me on how to move players?
var gameBoard = {
createBoard: function(dimension, mount, intialPosition) {
var mount = document.querySelector(mount);
if (!dimension || isNaN(dimension) || !parseInt(dimension, 10)) {
return false;
} else {
dimension = typeof dimension === 'string' ? parseInt(dimension, 10) : dimension;
var table = document.createElement('table'),
row = document.createElement('tr'),
cell = document.createElement('td'),
rowClone,
cellClone;
var output;
for (var r = 0; r < dimension; r++) {
rowClone = row.cloneNode(true);
table.appendChild(rowClone);
for (var c = 0; c < dimension; c++) {
cellClone = cell.cloneNode(true);
rowClone.appendChild(cellClone);
}
}
mount.appendChild(table);
output = gameBoard.enumerateBoard(table, intialPosition);
}
return output;
},
enumerateBoard: function(board) {
var rows = board.getElementsByTagName('tr'),
text = document.createTextNode(''),
rowCounter = 1,
size = rows.length,
cells,
cellsLength,
cellNumber,
odd = false,
control = 0;
for (var r = size - 1; r >= 0; r--) {
cells = rows[r].getElementsByTagName('td');
cellsLength = cells.length;
rows[r].className = r % 2 == 0 ? 'even' : 'odd';
odd = ++control % 2 == 0 ? true : false;
size = rows.length;
for (var i = 0; i < cellsLength; i++) {
if (odd == true) {
cellNumber = --size + rowCounter - i;
} else {
cellNumber = rowCounter;
}
cells[i].className = i % 2 == 0 ? 'even' : 'odd';
cells[i].id = cellNumber;
cells[i].appendChild(text.cloneNode());
cells[i].firstChild.nodeValue = cellNumber;
rowCounter++;
}
}
var lastRow = rows[0].getElementsByTagName('td');
lastRow[0].id = 'lastCell';
var firstRow = rows[9].getElementsByTagName('td');
firstRow[0].id = 'firstCell';
intialPosition();
return gameBoard;
}
};
window.onload = (function(e) {
gameBoard.createBoard(10, "#grid", intialPosition);
});
var face1 = new Image()
face1.src = "d1.gif"
var face2 = new Image()
face2.src = "d2.gif"
var face3 = new Image()
face3.src = "d3.gif"
var face4 = new Image()
face4.src = "d4.gif"
var face5 = new Image()
face5.src = "d5.gif"
var face6 = new Image()
face6.src = "d6.gif"
function rollDice() {
var randomdice = Math.floor(Math.random() * 6) + 1;
document.images["mydice"].src = eval("face" + randomdice + ".src")
if (randomdice == 6) {
alert('Congratulations! You got 6! Roll the dice again');
}
return randomdice;
}
function intialPosition() {
$("#firstCell").append($("#player1"));
$("#firstCell").append($("#player2"));
}
/*body {
background-image: url('snakesandladder2.png');
background-repeat: no-repeat;
background-size: 100%;
background-color: #4f96cb;
}*/
#game {
width: 80%;
margin-left: auto;
margin-right: auto;
display: table;
}
#gameBoardSection {
border: 3px inset #0FF;
border-radius: 10px;
width: 65%;
display: table-cell;
}
table {
width: 100%;
}
td {
border-radius: 10px;
width: 60px;
height: 60px;
line-height: normal;
vertical-align: bottom;
text-align: left;
border: 0px solid #FFFFFF;
position: relative;
}
table tr:nth-child(odd) td:nth-child(even),
table tr:nth-child(even) td:nth-child(odd) {
background-color: PowderBlue;
}
table tr:nth-child(even) td:nth-child(even),
table tr:nth-child(odd) td:nth-child(odd) {
background-color: SkyBlue;
}
#lastCell {
background-image: url('rotstar2_e0.gif');
background-repeat: no-repeat;
background-size: 100%;
}
#ladder {
position: absolute;
top: 300px;
left: 470px;
-webkit-transform: rotate(30deg);
z-index: 1;
opacity: 0.7;
}
#bigSnake {
position: absolute;
top: 20px;
left: 200px;
opacity: 0.7;
z-index: 1;
}
#diceAndPlayerSection {
background-color: lightpink;
border: 1px;
border-style: solid;
display: table-cell;
border-radius: 10px;
border: 3px inset #0FF;
width: 35%;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<link href="StyleSheet1.css" rel="stylesheet" />
<script src="jquery-2.1.4.min.js"></script>
</head>
<body>
<div id="game">
<div id="gameBoardSection">
<div id="grid"></div>
<div id="ladder">
<img src="oie_eRDOY2iqd5oQ.gif" />
</div>
<div id="bigSnake">
<img src="oie_485727sRN4KKBG.png" />
</div>
<div id="player1" style="position:absolute; top:10px; left:10px;">
<img src="humanPiece.png" />
</div>
<div id="player2" style="position:absolute; top:15px; left:5px;">
<img src="computerPiece.png" />
</div>
</div>
<div id="diceAndPlayerSection">
<div id="reset">
<button type="button" name="reset">New Game</button>
</div>
<div>
<button type="button" name="reset">Reset</button>
</div>
<div>
<button type="button" name="addPlayer">Add Player</button>
</div>
<div id="diceSection">
<img src="d1.gif" name="mydice" onclick="rollDice()" style="background-color: white;">
<!--<h2 id="status" style="clear:left;"></h2>-->
</div>
</div>
</div>
<script src="JavaScript1.js"></script>
</body>
</html>
I fell miserable about not being able to finish the game. I really need help. Thanks in advance.
Well, first of all this question has been already asked and answered on SO and table cells are just the same as usual elements :)
Since you're using jQuery anyway, you can use .detach()
var element = $('td:eq(0) span').detach();
$('td:eq(1)').append(element);
Here's a jsfiddle.
Or, as proposed in this answer, you can use a native js solution.

Categories

Resources