replace the table data with the selected data(javascript) - javascript

javascript beginner here, trying to code and learn.
I have a table filled with data (fetch from url) and that data is
{
"france": "paris",
"finland": "helsinki",
"sweden": "stockholm",
"tajikistan": "dushanbe",
"uzbekistan ": "toshkent",
"china": "peking",
"dole": {
"Key": "fhd699f"
}
}
and under the table I have a select box (the data of it also fetched from url) its data is this
[
{"nimi": "tili","id": "48385","somewhere": "nassau","somewhere2": "bamako","somewhere3": "rabat","somewhere4": "baku"},
{"nimi": "tili","id": "789642","somewhere": "windhoek","somewhere2": "podgorica","somewhere3": "niamey","somewhere4": "islamabad"}
]
i want to replace the table data with the selected data ( i mean everything) even table's <th> also, for example table's <th> is 'france' and value is 'paris' but after replace table's <th> should be 'nimi' and value 'tili' according to select box data.
here is my code (as you can see 'tajikistan','uzbekistan','china' for some reason not going to their places in table):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.3/css/all.css" integrity="sha384-UHRtZLI+pbxtHCWp1t77Bi1L4ZtiqrqD80Kn4Z8NTSRyMA2Fd33n5dQ8lWUE00s/" crossorigin="anonymous">
<style>
</style>
</head>
<body>
<div class="container">
<table class="table ">
<thead>
<tr>
<th class="table-success">france</th>
<th class="table-success">finland</th>
<th class="table-success">sweden</th>
</tr>
</thead>
<tbody id="tiedot">
</tbody>
<thead>
<tr>
<th class="table-success">tajikistan</th>
<th class="table-success">uzbekistan</th>
<th class="table-success">china</th>
</tr>
</thead>
<tbody id="tiedot2">
</tbody>
</table>
<select id="valittu" name="name"></select>
</div>
<script>
fetch(
"https://tdejdjd***",
{
method: "GET",
headers: {
"x-api-key": "i****y"
}
}
)
.then((res) => {
res
.json()
.then((data) => {
tableupdating(data, ['france','finland','sweden','tajikistan','uzbekistan','china']);
})
.catch((err) => {
console.log("ERROR: " + err);
});
});
function tableupdating(data, values) {
const totable = document.getElementById("tiedot");
const totable2 = document.getElementById("tiedot2");
totable.innerHTML = "";
totable2.innerHTML = "";
var komb = "";
var komb2 = "";
komb += "<tr>";
komb2 += "<tr>";
values.forEach(value => {
komb += "<td>" + data[value] + "</td>";
})
values.forEach(value => {
komb2 += "<td>" + data[value] + "</td>";
})
totable.insertAdjacentHTML("beforeend", komb);
totable2.insertAdjacentHTML("beforeend", komb2);
}
let dataArray;
fetch(
"https://tdejdjd***",
{
method: "GET",
headers: {
"x-api-key": "i****y"
}
}
)
.then((res) => {
res.json().then((data) => {
dataArray = data;
updateSelect(data, ['nimi','id']);
});
});
function updateSelect(data, values) {
for (var i = 0; i < data.length; i++) {
var Valittu = document.getElementById("valittu");
var option = document.createElement("option");
values.forEach(value => {
option.textContent += data[i][value] + ' '
})
Valittu.appendChild(option);
}
}
document.getElementById("valittu").addEventListener("change", function (event) {
const chosenID = event.target.value.split(" ")[1];
const chosenData = dataArray.filter((data) => data.id === chosenID)[0];
tableupdating(chosenData, ['nimi', 'id', 'somewhere','somewhere2','somewhere3','somewhere4']);
});
</script>
</body>
</html>
as spoken in chat, here is new code, it is working but for some reason these three are in same line and not on their places : komb += "<td>"+tiedot.tajikistan+"</td>";
komb += "<td>"+tiedot.uzbekistan+"</td>";
komb += "<td>"+tiedot.china+"</td></tr>";
code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.3/css/all.css" integrity="sha384-UHRtZLI+pbxtHCWp1t77Bi1L4ZtiqrqD80Kn4Z8NTSRyMA2Fd33n5dQ8lWUE00s/" crossorigin="anonymous">
<style>
</style>
</head>
<body onload="fillTheBox();">
<div class="container">
<table class="table" id="myTable">
<thead>
<tr>
<th class="table-success">france</th>
<th class="table-success">finland</th>
<th class="table-success">sweden</th>
</tr>
</thead>
<tbody id="tiedot">
</tbody>
<thead>
<tr>
<th class="table-success">tajikistan</th>
<th class="table-success">uzbekistan</th>
<th class="table-success">china</th>
</tr>
</thead>
</table>
<select id="valittu" name="name" onchange="changed()"></select>
</div>
<script>
fetch("https://qj",
{
method: "GET",
headers: {
"x-api-key": ""
}
}
).then(res =>{
res.json().then(tiedot => {
console.log(tiedot);
var komb ="";
komb +="<tr>";
komb += "<td>"+tiedot.france+"</td>";
komb += "<td>"+tiedot.finland+"</td>";
komb += "<td>"+tiedot.sweden+"</td>";
komb += "<td>"+tiedot.tajikistan+"</td>";
komb += "<td>"+tiedot.uzbekistan+"</td>";
komb += "<td>"+tiedot.china+"</td></tr>";
document.getElementById("tiedot").insertAdjacentHTML("beforeend", komb );
}
)
})
var dataArray = [
{ "nimi": "tili", "id": "48385", "somewhere": "nassau", "somewhere2": "bamako", "somewhere3": "rabat", "somewhere4": "baku" },
{ "nimi": "tili", "id": "789642", "somewhere": "windhoek", "somewhere2": "podgorica", "somewhere3": "niamey", "somewhere4": "islamabad" }
]
function fillTheBox() {
var selectBox = document.getElementById("valittu");
var option = document.createElement("option");
option.value = dataArray[0];
option.text = dataArray[0].nimi+' '+dataArray[0].id;
selectBox.add(option);
var option1 = document.createElement("option");
option1.value = dataArray[1];
option1.text = dataArray[1].id;
selectBox.add(option1);
}
function changed() {
var e = document.getElementById("valittu");
var selectedObjectID = e.options[e.selectedIndex].text;
chosenData = dataArray.filter((data) => data.id === selectedObjectID)[0];
var myTable = document.getElementById("myTable");
myTable.innerHTML = "";
generateTable(myTable, chosenData);
}
function generateTable(table, data) {
let row1 = table.insertRow();
row1.className = "table-success";
let row2 = table.insertRow();
let row3 = table.insertRow();
row3.className = "table-success";
let row4 = table.insertRow();
var counter = 1;
for (key in data) {
if (counter<=3) {
let cell = row1.insertCell();
let text = document.createTextNode(key);
cell.appendChild(text);
let cell2 = row2.insertCell();
let text2 = document.createTextNode(data[key]);
cell2.appendChild(text2);
} else {
let cell = row3.insertCell();
let text = document.createTextNode(key);
cell.appendChild(text);
let cell2 = row4.insertCell();
let text2 = document.createTextNode(data[key]);
cell2.appendChild(text2);
}
counter++;
}
}
</script>
</body>
</html>

I created a basic demo to show the logic. Firs of all give an id to your table. And create a onChange event for your select box. In your event function edit your table content with innerHTML property. Just focus on change() and generateTable() functions in my code
<body onload="fillTheBox();">
<div class="container">
<table class="table" id="myTable">
<thead>
<tr>
<th class="table-success">france</th>
<th class="table-success">finland</th>
<th class="table-success">sweden</th>
</tr>
</thead>
<tbody id="tiedot">
</tbody>
<thead>
<tr>
<th class="table-success">tajikistan</th>
<th class="table-success">uzbekistan</th>
<th class="table-success">china</th>
</tr>
</thead>
</table>
<select id="valittu" name="name" onchange="changed()"></select>
</div>
<script>
var dataArray = [
{ "nimi": "tili", "id": "48385", "somewhere": "nassau", "somewhere2": "bamako", "somewhere3": "rabat", "somewhere4": "baku" },
{ "nimi": "tili", "id": "789642", "somewhere": "windhoek", "somewhere2": "podgorica", "somewhere3": "niamey", "somewhere4": "islamabad" }
]
function fillTheBox() {
var selectBox = document.getElementById("valittu");
var option = document.createElement("option");
option.value = dataArray[0];
option.text = dataArray[0].id;
selectBox.add(option);
var option1 = document.createElement("option");
option1.value = dataArray[1];
option1.text = dataArray[1].id;
selectBox.add(option1);
}
function changed() {
var e = document.getElementById("valittu");
var selectedObjectID = e.options[e.selectedIndex].text;
chosenData = dataArray.filter((data) => data.id === selectedObjectID)[0];
var myTable = document.getElementById("myTable");
myTable.innerHTML = "";
generateTable(myTable, chosenData);
}
function generateTable(table, data) {
let row1 = table.insertRow();
row1.className = "table-success";
let row2 = table.insertRow();
row2.className = "table-success";
let row3 = table.insertRow();
row3.className = "table-success";
let row4 = table.insertRow();
row4.className = "table-success";
var counter = 1;
for (key in data) {
if (counter<=3) {
let cell = row1.insertCell();
let text = document.createTextNode(key);
cell.appendChild(text);
let cell2 = row2.insertCell();
let text2 = document.createTextNode(data[key]);
cell2.appendChild(text2);
} else {
let cell = row3.insertCell();
let text = document.createTextNode(key);
cell.appendChild(text);
let cell2 = row4.insertCell();
let text2 = document.createTextNode(data[key]);
cell2.appendChild(text2);
}
counter++;
}
}
</script>
</body>
</html>
UPDATE:
To separate the fields mentioned in question add a <tr> element between them.
komb +="<tr>";
komb += "<td>"+tiedot.france+"</td>";
komb += "<td>"+tiedot.finland+"</td>";
komb += "<td>"+tiedot.sweden+"</td>";
komb +="</tr><tr>";
komb += "<td>"+tiedot.tajikistan+"</td>";
komb += "<td>"+tiedot.uzbekistan+"</td>";
komb += "<td>"+tiedot.china+"</td></tr>";

Related

Is there any option where we can put all the respected email in that table header which is an array?

I have table with 4 headers and a array of mixed email id , how can i insert this using only JavaScript any idea?
<html>
<body>
<table>
<tr>
<th>Gmail</th>
<th>Hotmail</th>
<th>Yahoo</th>
<th>Others</th>
</tr>
<tbody>
</tbody>
</table>
<script type="text/JavaScript">
data= ["multiple emails with different domain name"];
</script>
</body>
</html>
<script type="text/JavaScript">
let data = [
'one#foo.co',
'two#gmail.com',
'three#hotmail.com',
'four#gmail.com',
'five#yahoo.com',
'six#bar.co'
];
let list = document.querySelector('table tbody');
let mapper = {
gmail: 0,
hotmail: 1,
yahoo: 2
};
data.forEach(email => {
let row = document.createElement('tr');
let domain = email.match(/(?<=#).+(?=\.)/);
let index = mapper[domain];
row.innerHTML = '<td></td><td></td><td></td><td></td>';
if (typeof index === 'undefined') {
index = 3;
}
row.children[index].innerText = email;
list.append(row);
});
</script>
Demo here link
Unable to edit #Sonjoy Samadder solution, so adding new answer with his code refactored.
let data = [
'one#foo.co',
'two#gmail.com',
'three#hotmail.com',
'four#gmail.com',
'five#yahoo.com',
'six#bar.co'
];
let list = document.querySelector('table tbody');
const groupedMails = data.reduce((acc, mailId) => {
const domain = mailId.match(/(?<=#).+(?=\.)/);
(acc[domain] || acc.others).push(mailId);
return acc;
}, {gmail: [], hotmail: [], yahoo: [], others: []});
addDataToTable(groupedMails);
function addDataToTable(groups) {
const maxRows = Object.values(groupedMails).reduce((e1, e2) => (e1.length > e2.length ? e1 : e2).length);
const colOrder = ['gmail', 'hotmail', 'yahoo', 'others'];
const tableEle = document.querySelector('table tbody');
tableEle.innerHTML = '';
for ( let i = 0; i < maxRows; i++) {
const tr = colOrder.reduce((acc, key) => {
const td = document.createElement('td');
td.innerText = groups[key][i] || '';
acc.append(td);
return acc;
}, document.createElement('tr'));
tableEle.append(tr);
}
}
<table>
<thead>
<tr>
<th>Gmail</th>
<th>Hotmail</th>
<th>Yahoo</th>
<th>Others</th>
</tr>
</thead>
<tbody></tbody>
</table>

How to get tr element using ParentNode

Use the check boxes to display the tasks that have the active button pressed when you click the "In Progress" check, and the completion button when you click the "Complete" check.
I am trying to implement that only the tasks that are present are displayed.
Currently, when the check box is set to "Complete", "Button only" is hidden.
I have tried the following:
const doneTasks = document.getElementsByTagName('tr');
I tried to get the tr element as above, but it didn't work.
I am thinking that if I get the tr element, the entire task will be hidden, while the button element has been obtained to hide it now.
Please tell me to someone.
{
document.addEventListener('DOMContentLoaded', () => {
const addTaskTrigger = document.getElementsByClassName('addTask-trigger')[0];
const addTaskTarget = document.getElementsByClassName('addTask-target')[0];
const addTaskValue = document.getElementsByClassName('addTask-value')[0];
const radioWork = document.getElementById('radio-work');
const radioDone = document.getElementById('radio-done');
let nextId = 0;
const todos = [];
//Taskとidを作成
const addTask = (task, id, tableItem) => {
const idSpanTd = document.createElement('td');
const taskSpanTd = document.createElement('td');
//タスク追加時にtodosにtodoを追加
//要素内のHTML文章を変更する
idSpanTd.innerText = id;
taskSpanTd.innerText = task;
//生成したテーブル要素をブラウザに表示する
tableItem.append(idSpanTd);
tableItem.append(taskSpanTd);
addTaskTarget.append(tableItem);
};
//Button要素を生成する
const addButton = (tableItem, removeButton, createButton) => {
const createButtonTd = document.createElement('td');
const removeButtonTd = document.createElement('td');
//要素内のHTML文章を変更する
createButton.innerText = '作業中';
removeButton.innerText = '削除';
//生成したテーブル要素をブラウザに表示する
tableItem.append(createButtonTd);
tableItem.append(removeButtonTd);
addTaskTarget.append(tableItem);
//生成したbutton要素を生成する
createButtonTd.append(createButton);
removeButtonTd.append(removeButton);
};
//追加ボタンをクリックした際にtd要素を追加する処理を行う
addTaskTrigger.addEventListener('click', () => {
const task = addTaskValue.value;
const tableItem = document.createElement('tr');
const removeButton = document.createElement('button');
const createButton = document.createElement('button');
addTask(task, nextId++, tableItem);
addButton(tableItem, removeButton, createButton);
addTaskValue.value = '';
// //削除ボタンを押した時にタスクを削除する
const deleteElement = (a) => {
const tableTag = a.target.closest('tr');
if (tableTag) tableTag.remove();
updateId();
}
removeButton.addEventListener('click', deleteElement, false);
//ボタンを押したら作業中、完了中と変わる
createButton.addEventListener('click', (a) => {
if (createButton.textContent === "作業中") {
createButton.textContent = "完了";
const doneParent = a.target.parentNode;
doneParent.className = 'workDone';/*完了class*/
} else {
createButton.textContent = "作業中";
const workParent = a.target.parentNode;
workParent.className = 'work';/*作業中class*/
}
});
})
//todoの状態を管理
const todo = [{task: 'taskSpanTd',status: '作業中'},{task: 'taskSpanTd',status: '完了'}]
todos.push(todo);
/*ラジオボタン作業中を押下時の処理*/
radioDone.addEventListener('click', function () {
let workTasks = document.getElementsByClassName('work');
workTasks = Array.from(tr);
if (radioWork.checked.tr=== true) {
workTasks.forEach(function (workTasks) {
workTasks.style.display = "";
})
} else {
workTasks.forEach(function (workTasks) {
workTasks.style.display = "none";
})
}
})
// ラジオボタン完了押下時処理
radioWork.addEventListener('click', function () {
let doneTasks = document.getElementsByClassName('workDone');
doneTasks = Array.from(tr);
if (radioDone.checked.tr === true) {
doneTasks.forEach(function (doneTasks) {
doneTasks.style.display = "";
})
} else {
doneTasks.forEach(function (doneTasks) {
doneTasks.style.display = "none";
})
}
})
// 連番 再振り直し
const updateId = () => {
const tbody = document.getElementsByTagName("tbody")[0];
const taskList = tbody.getElementsByTagName('tr');
nextId = 0;
Array.from(taskList, tr => {
tr.getElementsByTagName('td')[0].textContent = nextId;
nextId++
});
}
});
}
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="css/style.css">
<title>Todoリスト</title>
</head>
<body>
<h1>Todoリスト</h1>
<p>
<input type="radio" name="task" value="1" checked ="checked">全て
<input type="radio" id="radio-work" name="task" value="2">作業中
<input type="radio" id="radio-done" name="task" value="3">完了
</p>
<p></p>
<table>
<thead>
<th>ID</th>
<th>コメント</th>
<th>状態</th>
<th></th>
</thead>
<tbody class="addTask-target" id="tbody"></tbody>
</table>
<h2>新規タスクの追加</h2>
<input class="addTask-value" type="text" />
<button class="addTask-trigger" type="button">追加</button>
<script src="js/main.js"></script>
</body>
</html>
It's not good idea to select the tr tag by using it parent for example you can select child elements of div like
var div = document.getElementById('parent');
div.firstElementChild.style.background = 'red';
div.lastElementChild.style.background = 'blue';
#parent {
width: 100px;
height: 100px;
position: relative;
}
.child {
width: 100%;
height: 50%;
}
<div id="parent">
<div class="child"></div>
<div class="child"></div>
</div>
but this can't be done on table if you you do it you will not point only one tr it will be applied on all tr like the following example
table = document.getElementsByTagName('table')[0];
table.firstElementChild.style.background = 'grey';
table.lastElementChild.style.background = 'green';
<table border="1px" cellpadding="5px">
<tr>
<th>Names</th>
</tr>
<tr>
<td>Eric</td>
</tr>
<tr>
<td>Ivan</td>
</tr>
</table>
so better select all table row in table and loop on the to get one by one like
tr = document.getElementsByTagName('tr');
for (var i = 0; i < tr.length; i++) {
if (i == 0) {
tr[i].style.background = 'green';
} else if (i == 1) {
tr[i].style.background = 'grey';
} else {
tr[i].style.background = 'cyan';
}
}
<table border="1px" cellpadding="5px">
<tr>
<th>Names</th>
</tr>
<tr>
<td>Eric</td>
</tr>
<tr>
<td>Ivan</td>
</tr>
</table>

Generate HTML table from loaded json file not working

I need t ogenerate an HTML table from a json file. The is loading OK, I can see the values in console.log, but I don't get how to pass these values in the other function (generate table function)
Here's my code:
<!DOCTYPE html>
<html lang="fr-CA" dir="ltr">
<head>
<meta charset="utf-8">
<title>Tableau de l'inventaire - API JSON</title>
</head>
<body>
<h2>Voitures en inventaire</h2>
<table id="myTable">
<thead>
<tr>
<th>No Stock</th>
<th>Marque</th>
<th>Modèle</th>
<th>Année</th>
</tr>
</thead>
</table>
<button type="button" onclick="loadTable()">Charge Content</button>
<script type="text/javascript">
// Loading json file = OK
function loadXMLDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// JSON.parse(this.responseText);
var i = JSON.parse(this.responseText);
// var x = document.getElementById("myTable").innerHTML = this.responseText
// console.log(jsonObj);
}
};
xhttp.open("GET", "voituresRecords.json", true);
xhttp.send();
}
// Generate table from json data = Not working
function loadTable(loadXMLDoc) {
var x = document.getElementById('myTable');
for(var i = 1; i < array.length; i++) {
var newRow = table.insertRow(table.length);
for(var j = 0; j < array[i].length; j++) {
var cell = newRow.insertCell(j);
cell.innerHTML = array[i][j];
}
}
}
</script>
</body>
</html>
And here's the json data from file:
[{"no_stock":"AC5678","marque":"Hyundai","modele":"Accent","annee":"2006"},
{"no_stock":"EL5320","marque":"Hyundai","modele":"Elantra","annee":"2018"},
{"no_stock":"KO4301","marque":"Hyundai","modele":"Kona","annee":"2018"},
{"no_stock":"TO4210","marque":"Hyundai","modele":"Tucson","annee":"2017"}]
Thanks for any help!
could be very more easy with a fetch : https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API
Your code should that way
<h2>Voitures en inventaire</h2>
<table id="myTable">
<thead>
<tr>
<th>No Stock</th>
<th>Marque</th>
<th>Modèle</th>
<th>Année</th>
</tr>
</thead>
<tbody></tbody>
</table>
<button type="button" onclick="loadTable()">Charge Content</button>
const myTableBody = document.querySelector('#myTable tbody')
function loadTable() {
fetch('voituresRecords.json')
.then(resp => resp.json())
.then(data => {
data.forEach( info=>{
let newRow = myTableBody.insertRow()
newRow.insertCell().textContent = info.no_stock
newRow.insertCell().textContent = info.marque
newRow.insertCell().textContent = info.modele
newRow.insertCell().textContent = info.annee
})
})
.catch(error => console.error(error))
}

changing forEach into for loop

Javascript beginner here, trying to learn by coding, at the moment i'm trying to learn 'forEach' and 'for', here i have a code where it is working with 'forEach' i'm trying to change it into 'for loop', like this(dont know if i'm doing right here ?) if possibly somebody could write separate 'for loops' for this ? would be good for new programmers.
for (var i = 0; i < arvvoja.length; i++) {
option.textContent += dataa[i][arvvoja] + " ";
});
without any success, here is my code :
let animals
let animalCols = ['Animal', 'Animal 2']
let peopleCols = ['Person', 'Person 2']
function myFunction() {
paivitys(animals, animalCols)
}
function paivitys(dataa, arvvoja) {
console.log(dataa);
//----
if (dataa.hasOwnProperty("animal")) {
document.getElementById("1name").innerHTML = dataa.animal;
} else {
document.getElementById("1name").innerHTML = dataa.person;
}
//----
if (dataa.hasOwnProperty("animal2")) {
document.getElementById("2name").innerHTML = dataa.animal2;
} else {
document.getElementById("2name").innerHTML = dataa.person2;
}
document.getElementById("1name1").innerHTML = arvvoja[0];
document.getElementById("2name1").innerHTML = arvvoja[1];
//-----
document.getElementById("id").innerHTML = dataa.id;
}
function paivitaselekt(dataa, arvvoja) {
for (var i = 0; i < dataa.length; i++) {
var valitse = document.getElementById("Select");
var option = document.createElement("option");
arvvoja.forEach((value) => {
option.textContent += dataa[i][value] + " ";
});
valitse.appendChild(option);
}
}
animals = {
"animal": "tiger",
"animal2": "lion",
"id": "54321",
"dole": {
"Key": "fhd699f"
}
}
paivitys(animals, animalCols);
let kokoarray;
people = [{
"person": "kaka",
"person2": "julle",
"id": "9874",
},
{
"person": "Ronaldo",
"person2": "jussi",
"id": "65555",
}
]
kokoarray = people;
paivitaselekt(kokoarray, ["person", "id"]);
document.getElementById("Select").addEventListener("change", function(event) {
const otettutunnsite = event.target.value.split(" ")[1];
const otettutieto = kokoarray.filter((dataa) => dataa.id === otettutunnsite)[0];
paivitys(otettutieto, peopleCols);
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width" />
<link
rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css"
/>
<link
rel="stylesheet"
href="https://use.fontawesome.com/releases/v5.6.3/css/all.css"
integrity="sha384UHRtZLI+pbxtHCWp1t77Bi1L4ZtiqrqD80Kn4Z8NTSRyMA2Fd33n5dQ8lWUE00s/"
crossorigin="anonymous"
/>
<style>
</style>
</head>
<body>
<div class="">
<table class="table ">
<thead>
<tr>
<th id="1name1" class="table-success">Animal</th>
<th id="2name1" class="table-success">Animal</th>
<th class="table-success">id</th>
</tr>
</thead>
<tbody>
<th id="1name"></th>
<th id="2name"></th>
<th id="id"></th>
</tbody>
</table>
<select id="Select" ></select>
<button onclick="myFunction()">backtozero</button>
</div> </body>
</html>
Use a different variable in the inner loop:
var i, j;
for (i = 0; i < dataa.length; i++) {
var valitse = document.getElementById("Select");
var option = document.createElement("option");
for (j = 0; j < arvvoja.length; j++) {
option.textContent += dataa[i][arvvoja[j]] + " ";
}
valitse.appendChild(option);
}

Updating row ID when swapping HTML table rows

I've been messing with manipulating HTML tables for the past few weeks and I've come across a problem I am not sure how to fix. So the collection of rows for a table can be iterated over like an array, but if you've switched out the rows a lot, won't the IDs be mixed and doesn't the browser rely on the IDs as the way to iterate over the row objects? I'm running into a problem (probably due to a lack of understanding) where the rows eventually stop moving or one row gets duplicated on top of another. Should I somehow be updating the row's ID each time it is moved? Here is my source so far for this function.
function swap(rOne, rTwo, tblID) {
tblID.rows[rOne].setAttribute('style', 'background-color:#FFFFFF');
var tBody = tblID.children[0];
var rowOne;
var rowTwo;
if (rOne > rTwo) {
rowOne = rOne;
rowTwo = rTwo;
}
else {
rowOne = rTwo;
rowTwo = rOne;
}
var swapTempOne = tblID.rows[rowOne].cloneNode(true);
var swapTempTwo = tblID.rows[rowTwo].cloneNode(true);
hiddenTable.appendChild(swapTempOne);
hiddenTable.appendChild(swapTempTwo);
tblID.deleteRow(rowOne);
var rowOneInsert = tblID.insertRow(rowOne);
var rowOneCellZero = rowOneInsert.insertCell(0);
var rowOneCellOne = rowOneInsert.insertCell(1);
var rowOneCellTwo = rowOneInsert.insertCell(2);
var rowOneCellThree = rowOneInsert.insertCell(3);
rowOneCellZero.innerHTML = hiddenTable.rows[2].cells[0].innerHTML;
rowOneCellOne.innerHTML = hiddenTable.rows[2].cells[1].innerHTML;
rowOneCellTwo.innerHTML = hiddenTable.rows[2].cells[2].innerHTML;
rowOneCellThree.innerHTML = hiddenTable.rows[2].cells[3].innerHTML;
tblID.deleteRow(rowTwo);
var rowTwoInsert = tblID.insertRow(rowTwo);
var rowTwoCellZero = rowTwoInsert.insertCell(0);
var rowTwoCellOne = rowTwoInsert.insertCell(1);
var rowTwoCellTwo = rowTwoInsert.insertCell(2);
var rowTwoCellThree = rowTwoInsert.insertCell(3);
rowTwoCellZero.innerHTML = hiddenTable.rows[1].cells[0].innerHTML;
rowTwoCellOne.innerHTML = hiddenTable.rows[1].cells[1].innerHTML;
rowTwoCellTwo.innerHTML = hiddenTable.rows[1].cells[2].innerHTML;
rowTwoCellThree.innerHTML = hiddenTable.rows[1].cells[3].innerHTML;
tblID.rows[rowOne].setAttribute('onclick', 'chkThis(event, this)');
tblID.rows[rowTwo].setAttribute('onclick', 'chkThis(event, this)');
for (iHiddenDelete = 2; iHiddenDelete >= 1; iHiddenDelete--) {
hiddenTable.deleteRow(iHiddenDelete);
}
}
EDIT: Adding HTML for page and the function for moving between tables which I suspect is causing the issue.
<body>
<form>
<input value="0" type="text" id="cubesum" size="5"/>
<input value="0" type="text" id="wgtsum" size="5"/>
</form>
<form>
<table id="tblSource">
<thead>
<tr>
<th> </th>
<th>Order</th>
<th>Cube</th>
<th>Weight</th>
<th>Move</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<button type="button" onclick="move('tblSource','tblTarget')" style="width: 58px">To Trucks (Down)</button>
<button type="button" onclick="move('tblTarget', 'tblSource')" style="width: 58px">To Orders (Up)</button>
</form>
<form>
<table id="tblTarget">
<thead>
<tr>
<th> </th>
<th>Order</th>
<th>Cube</th>
<th>Weight</th>
<th>Move</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</form>
<table id="hiddenTable" style="display: none"> <!--this table is hidden! -->
<thead>
<tr>
<th> </th>
<th>Order</th>
<th>Cube</th>
<th>Weight</th>
<th>Move</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</body>
</html>
FUNCTION STARTS HERE
function move(from, to) {
var frTbl = document.getElementById(from);
var toTbl = document.getElementById(to);
chkArray.length = 0;
cbsMove = frTbl.getElementsByTagName('input');
for (var oChk = 0; oChk < cbsMove.length; oChk++) {
if (cbsMove[oChk].type == 'checkbox') {
if (cbsMove[oChk].checked == true) {
var prntRow = cbsMove[oChk].parentNode.parentNode;
var prntRowIdx = prntRow.rowIndex;
chkArray.push(prntRowIdx);
cbsMove[oChk].checked = false;
}
}
}
for (iMove = chkArray.length -1; iMove >= 0; iMove--) {
var num = chkArray[iMove];
var row = frTbl.rows[num];
var cln = row.cloneNode(true);
toTbl.appendChild(cln);
frTbl.deleteRow(num);
}
sum();
}
So it turns out that my row cloning for moving between tables was causing malformed HTML where the rows would not longer be inside the table body tags. In addition, not trusting the browser to keep track of the button IDs and using the button IDs to setAttributes to the button also caused button ID overlap eventually. So, I got rid of the node cloning and did the row moving between tables the manual way and used innerHTML to add the function call inside the buttons. Upon further reflection, I've come to learn that some people actually make functions that handle ALL button clicks without calling them inside the button and route them to the proper function depending on the ID or other factors such as parent nodes of the button. Perhaps that is best. The main trick here is to STICK TO ONE METHOD. I was all over the place in how I manipulated the tables and it broke things. Here is the working source for those looking to do similar things.
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<style type="text/css">
#selectSource {
width: 320px;
}
#selectTarget {
width: 320px;
}
table, th, td
{
border: 1px solid black;
}
</style>
<title>Loader</title>
<script>
var chkArray = [];
var data = [];
var tmpArray = [];
var iChk = 0;
var swap;
window.onload = function () {
var load = document.getElementById('selectSource')
loadFromAJAX();
}
function loadFromAJAX()
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var rawData = xmlhttp.responseText;
data = JSON.parse(rawData);
for (iData = 0; iData < data.length; iData++) {
newRow = document.getElementById('tblSource').insertRow(iData + 1);
var dn = "dn" + (iData + 1);
var up = "up" + (iData + 1);
cel0 = newRow.insertCell(0);
cel1 = newRow.insertCell(1);
cel2 = newRow.insertCell(2);
cel3 = newRow.insertCell(3);
cel4 = newRow.insertCell(4);
cel0.innerHTML = "<input type='checkbox' name='chkbox'>";
cel1.innerHTML = data[iData].num;
cel2.innerHTML = data[iData].cube;
cel3.innerHTML = data[iData].wgt;
cel4.innerHTML = "<button type='button' onclick=moveUp(this)>up</button><button type='button' onclick=moveDn(this)>down</button>";
}
}
}
xmlhttp.open("POST","http://192.168.3.2/cgi-bin/rims50.cgi/json.p",true);
xmlhttp.send();
}
function moveUp(mvThisRow) {
var mvThisRowRow = mvThisRow.parentNode.parentNode;
var mvThisRowTbl = mvThisRowRow.parentNode.parentNode;
var mvThisRowIndex = mvThisRowRow.rowIndex;
var mvThisRowTblLngth = mvThisRowTbl.rows.length;
var mvFrRow = mvThisRowTbl.rows[mvThisRowIndex];
var mvToRow = mvThisRowIndex - 1;
var mvThisDn = "dn" + (mvToRow) + mvThisRowTbl;
var mvThisUp = "up" + (mvToRow) + mvThisRowTbl;
if (mvThisRowIndex - 1 !== 0) {
moveToRow = mvThisRowTbl.insertRow(mvToRow);
mvRowCel0 = moveToRow.insertCell(0);
mvRowCel1 = moveToRow.insertCell(1);
mvRowCel2 = moveToRow.insertCell(2);
mvRowCel3 = moveToRow.insertCell(3);
mvRowCel4 = moveToRow.insertCell(4);
mvRowCel0.innerHTML = "<input type='checkbox' name='chkbox'>";
mvRowCel1.innerHTML = mvFrRow.cells[1].innerHTML;
mvRowCel2.innerHTML = mvFrRow.cells[2].innerHTML;
mvRowCel3.innerHTML = mvFrRow.cells[3].innerHTML;
mvRowCel4.innerHTML = "<button type='button' onclick=moveUp(this)>up</button><button type='button' onclick=moveDn(this)>down</button>";
mvThisRowTbl.deleteRow(mvThisRowIndex +1);
}
else {
alert("You can't move the top row 'up' try moving it 'down'.");
}
}
function moveDn(mvThisRow) {
var mvThisRowRow = mvThisRow.parentNode.parentNode;
var mvThisRowTbl = mvThisRowRow.parentNode.parentNode;
var mvThisRowTblLngth = mvThisRowTbl.rows.length;
var mvThisRowIndex = mvThisRowRow.rowIndex;
if (mvThisRowIndex + 1 !== mvThisRowTblLngth) {
var mvFrRow = mvThisRowTbl.rows[mvThisRowIndex];
var mvToRow = mvThisRowIndex + 2;
var moveToRow = mvThisRowTbl.insertRow(mvToRow);
var dn = "dn" + (mvToRow) + mvThisRowTbl;
var up = "up" + (mvToRow) + mvThisRowTbl;
mvRowCel0 = moveToRow.insertCell(0);
mvRowCel1 = moveToRow.insertCell(1);
mvRowCel2 = moveToRow.insertCell(2);
mvRowCel3 = moveToRow.insertCell(3);
mvRowCel4 = moveToRow.insertCell(4);
mvRowCel0.innerHTML = "<input type='checkbox' name='chkbox'>";
mvRowCel1.innerHTML = mvFrRow.cells[1].innerHTML;
mvRowCel2.innerHTML = mvFrRow.cells[2].innerHTML;
mvRowCel3.innerHTML = mvFrRow.cells[3].innerHTML;
mvRowCel4.innerHTML = "<button type='button' onclick=moveUp(this)>up</button><button type='button' onclick=moveDn(this)>down</button>";
mvThisRowTbl.deleteRow(mvThisRowIndex);
}
else {
alert("You can't move the bottom row 'down' try moving it 'up'.");
}
}
function sum() {
var trgTbl = document.getElementById('tblTarget');
var tblLength = trgTbl.rows.length;
var sumAddCube = 0;
var sumAddWgt = 0;
document.getElementById("cubesum").setAttribute("value", sumAddCube);
document.getElementById("wgtsum").setAttribute("value", sumAddWgt);
for (iSum = 1; iSum < tblLength; iSum++) {
celCubeNum = trgTbl.rows[iSum].cells[2].innerHTML;
celWgtNum = trgTbl.rows[iSum].cells[3].innerHTML;
sumAddCube = parseInt(sumAddCube) + parseInt(celCubeNum);
sumAddWgt = parseInt(sumAddWgt) + parseInt(celWgtNum);
}
document.getElementById("cubesum").setAttribute("value", sumAddCube);
document.getElementById("wgtsum").setAttribute("value", sumAddWgt);
}
function move(from, to) {
var frTbl = document.getElementById(from);
var toTbl = document.getElementById(to);
chkArray.length = 0;
cbsMove = frTbl.getElementsByTagName('input');
for (var oChk = 0; oChk < cbsMove.length; oChk++) {
if (cbsMove[oChk].type == 'checkbox') {
if (cbsMove[oChk].checked == true) {
var prntRow = cbsMove[oChk].parentNode.parentNode;
var prntRowIdx = prntRow.rowIndex;
chkArray.push(prntRowIdx);
cbsMove[oChk].checked = false;
}
}
}
for (iMove = chkArray.length -1; iMove >= 0; iMove--) {
var num = chkArray[iMove];
var row = frTbl.rows[num];
var toRow = toTbl.rows.length
moveRow = toTbl.insertRow(toRow);
var dn = "dn" + (toRow) + toTbl;
var up = "up" + (toRow) + toTbl;
mvCel0 = moveRow.insertCell(0);
mvCel1 = moveRow.insertCell(1);
mvCel2 = moveRow.insertCell(2);
mvCel3 = moveRow.insertCell(3);
mvCel4 = moveRow.insertCell(4);
mvCel0.innerHTML = "<input type='checkbox' name='chkbox'>";
mvCel1.innerHTML = row.cells[1].innerHTML;
mvCel2.innerHTML = row.cells[2].innerHTML;
mvCel3.innerHTML = row.cells[3].innerHTML;
mvCel4.innerHTML = "<button type='button' onclick=moveUp(this)>up</button><button type='button' onclick=moveDn(this)>down</button>";
frTbl.deleteRow(num);
}
sum();
}
</script>
</head>
<body>
<form>
<input value="0" type="text" id="cubesum" size="5"/>
<input value="0" type="text" id="wgtsum" size="5"/>
</form>
<form>
<table id="tblSource">
<thead>
<tr>
<th> </th>
<th>Order</th>
<th>Cube</th>
<th>Weight</th>
<th>Move</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<button type="button" onclick="move('tblSource','tblTarget')" style="width: 58px">To Trucks (Down)</button>
<button type="button" onclick="move('tblTarget', 'tblSource')" style="width: 58px">To Orders (Up)</button>
</form>
<form>
<table id="tblTarget">
<thead>
<tr>
<th> </th>
<th>Order</th>
<th>Cube</th>
<th>Weight</th>
<th>Move</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</form>
<table id="hiddenTable" style="display: none"> <!--this table is hidden! -->
<thead>
<tr>
<th> </th>
<th>Order</th>
<th>Cube</th>
<th>Weight</th>
<th>Move</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</body>
</html>

Categories

Resources