how to show data to table from an array of objects - javascript

I am trying to make a data table from user input. i found out this solution that i am making objects from user input and pushing them to an array. after that, I am doing a for loop to make td. but somehow those datas are not coming line by line but they are coming side by side. what I am doing wrong here and every time I am refreshing the page the array is getting empty how to prevent this help me out tnx.
const form = document.getElementById("form");
const carDatas = [];
class Car {
constructor(plate, carMaker, carModel, carOwner, carPrice, carColor) {
(this.plate = plate),
(this.carMaker = carMaker),
(this.carModel = carModel),
(this.carOwner = carOwner),
(this.carPrice = carPrice),
(this.carColor = carColor);
}
}
form.addEventListener("submit", (e) => {
const plate = document.getElementById("plate").value;
const carMaker = document.getElementById("carMaker").value;
const carModel = document.getElementById("carModel").value;
const carOwner = document.getElementById("carOwner").value;
const carPrice = document.getElementById("carPrice").value;
const carColor = document.getElementById("carColor").value;
const carDetails = new Car(
plate,
carMaker,
carModel,
carOwner,
carPrice,
carColor
);
carDatas.push(carDetails);
console.log(carDetails);
for (let i = 0; i < carDatas.length; i++) {
document.getElementById(
"data"
).innerHTML = ` <td>${carDatas[i].plate} </td>
<td>${carDatas[i].carMaker} </td>
<td>${carDatas[i].carModel} </td>
<td>${carDatas[i].carOwner} </td>
<td>${carDatas[i].carPrice} </td>
<td>${carDatas[i].carColor} </td>`;
}
e.preventDefault();
});
and here is my HTML for the table
<div class="database">
<h1>Cars Database</h1>
<table>
<tr>
<th>LICENCE</th>
<th>MAKER</th>
<th>MODEL</th>
<th>OWNER</th>
<th>PRICE</th>
<th>COLOR</th>
</tr>
<tr id="data"></tr>
</table>
</div>

<pre>This is what I recommend I changed your code to add <tr></tr> to each line that's to be created and wrap your <tr> inbetween and tbody tag and use the first line has a head.</pre>
<pre>For the code:</pre>
<code>
for (let i = 0; i < carDatas.length; i++) {
document.getElementById(
"data"
).innerHTML = `<tr><td>${carDatas[i].plate} </td>
<td>${carDatas[i].carMaker} </td>
<td>${carDatas[i].carModel} </td>
<td>${carDatas[i].carOwner} </td>
<td>${carDatas[i].carPrice} </td>
<td>${carDatas[i].carColor} </td> </tr>`;
}
e.preventDefault();
<body>
<div class="database">
<h1>Cars Database</h1>
<table>
<thead>
<tr>
<th>LICENCE</th>
<th>MAKER</th>
<th>MODEL</th>
<th>OWNER</th>
<th>PRICE</th>
<th>COLOR</th>
</tr>
</thead>
<tbody id="data"> <tbody>
</table>
</div>
</body>
</code>

Related

How to remove an item using class? : javascript

I made a table to show some items and i want it to be cleared once i press the clear button.
Now the main problem is that my tr that i want to remove does'nt take tbody as its parent.
Here's my html:
<table>
<tbody id="stuffCarrier"></tbody>
</table>
and here's my javascript to remove the items:
document.getElementById("clearList").onclick = function () {
Array.from(document.getElementsByClassName("removeds")).forEach((e, i, arr) => {
document.getElementById("stuffCarrier").removeChild(e);
console.log(i, e, e.parentElement, arr);
});
localStorage.removeItem("CarriedStuff");
And here's my javascript how i added the items:
const stuffCarrier = document.getElementById("stuffCarrier");
stuffCarrier.innerHTML = `<tr>
<th class="stuffs">Quantity</th>
<th class="stuffs" style="color:red">Stuff</th>
<th class="stuffs" style="color:chartreuse">Cost</th>
</tr>
`;
showStuff.forEach(e => {
stuffCarrier.innerHTML += `<tr class="stuffs removeds">
<td>${e[2]}</td>
<td style="color:blue">${e[0]}</td>
<td style="color:white">${e[1] * e[2]}</td>
</tr>
`;
});
Array.from(document.getElementsByClassName("removeds")).forEach(d=>d.remove())
First try to add tr as childElement of stuffCarrier like this:
const stuffCarrier = document.getElementById("stuffCarrier");
childElement = `<tr>
<th class="stuffs">Quantity</th>
<th class="stuffs" style="color:red">Stuff</th>
<th class="stuffs" style="color:chartreuse">Cost</th>
</tr>
`;
stuffCarrier.appendChild(childElement);
Even within the for loop. Then I think you will be able to remove tr as removeChild().
Or you can directly remove all the selected elements like this:
Array.from(document.getElementsByClassName("removeds")).forEach(d=>d.remove()) without using removeChild() method.
I hope it helps.
you need a closing function bracket before the localstorage line, but other than that it works??
<input id='clearList' value='clear' type='button' />
<table>
<tbody id="stuffCarrier"></tbody>
</table>
<script>
var showStuff=[
[1,2,3],[4,5,6]
]
const stuffCarrier = document.getElementById("stuffCarrier");
stuffCarrier.innerHTML = `
<tr>
<th class="stuffs">Quantity</th>
<th class="stuffs" style="color:red">Stuff</th>
<th class="stuffs" style="color:chartreuse">Cost</th>
</tr>
`;
showStuff.forEach(e => {
stuffCarrier.innerHTML += `
<tr class="stuffs removeds">
<td>${e[2]}</td>
<td style="color:blue">${e[0]}</td>
<td style="color:cyan">${e[1] * e[2]}</td>
</tr>
`;
});
document.getElementById("clearList").onclick = function () {
var nl=document.getElementsByClassName("removeds");
Array.from(nl).forEach((e, i, arr) => {
document.getElementById("stuffCarrier").removeChild(e);
console.log(i, e, e.parentElement, arr);
});
}
</script>

In the below code I want to get the index value of rs using its Id and want to get its position

<table>
<tr>
<td id="1">Adi</td>
<td id="2">Aman</td>
</tr>
</table>
In the above code, I want to know the position of Aman using its id
You can try something like this:
html:
<table id="myTable">
<tr>
<td id="1">Adi</td>
<td id="2">Aman</td>
</tr>
</table>
js:
function getIdFromTable(searchValue)
{
var t = document.getElementById("myTable");
var trs = t.getElementsByTagName("tr");
var tds = null;
for (var i=0; i<trs.length; i++)
{
tds = trs[i].getElementsByTagName("td");
for (var n=0; n<tds.length;n++)
{
if (tds[n].innerText === searchValue) {
return tds[n].id;
}
}
}
}
getIdFromTable('Aman'); // will return 2
Easiest way to find position by id would be using prevAll().length. Something like this:
function findPositionById(id){
return $('#mytable').find('#'+id).prevAll().length
}
console.log('Adi Position', findPositionById(1));
console.log('Aman Position', findPositionById(2));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<table id="mytable">
<tr>
<td id="1">Adi</td>
<td id="2">Aman</td>
</tr>
</table>

How to perform operations on selected rows in checkbox in a table in HTML

I have a table and I want to perform some operations(suppose doing output of selected rows in alert) on the rows which the user have checked on.
Following is my approach which is failing miserably-
<html>
<head>
<title>Introduction</title>
<script>
function kro(){
var x = document.getElementsByName('checks');
for (var i = 0;i < x.length;i++){
if(x[i].checked == 1)
var selecteddata+=x[i].value+"\n";
}
alert(selecteddata)
}
</script>
</head>
<body>
<table>
<thead>
<tr>
<th>UserName</th>
<th>Post</th>
<th>Comments</th>
<th>Select</th>
</tr>
</thead>
<tbody>
<tr>
<td>Ram</td>
<td>Sahi hai</td>
<td>Ravan:No</td>
<td><input type = "checkbox" name = "checks" id='one'/> </td>
</tr>
<tr>
<td>Ravan</td>
<td>Kidnap done</td>
<td>Ram:I'll kill you</td>
<td><input type = "checkbox" name = "checks" id='two'/> </td>
</tbody>
<p id = "check" ></p>
<button onclick="kro()">
Result
</button>
</body>
</html>
Following is my table-
I want to perform further operations on the selected row ,in the code ,I just want to output the selected rows using alert.
How to do that?
Expected Output-
if first row is checked then
Ram Sahi hai Ravan:No
var selecteddata+=x[i].value+"\n"; line will throw an error, So declare the variable outside the for loop. Also you need to set a value to checkbox otherwise it will so on
To get the content from all the td get the parent of the checkbox and get the closest tr. Then get text from each of the td and add it in a local variable of the if block
function kro() {
var x = document.getElementsByName('checks');
var selecteddata = '';
for (var i = 0; i < x.length; i++) {
if (x[i].checked) {
let _tt = '';
x[i].closest('tr').querySelectorAll('td').forEach(function(item) {
_tt += item.textContent.trim();
})
selecteddata += _tt + "\n";
}
}
alert(selecteddata)
}
<table>
<thead>
<tr>
<th>UserName</th>
<th>Post</th>
<th>Comments</th>
<th>Select</th>
</tr>
</thead>
<tbody>
<tr>
<td>Ram</td>
<td>Sahi hai</td>
<td>Ravan:No</td>
<td><input type="checkbox" name="checks" id='one' value='test1' /> </td>
</tr>
<tr>
<td>Ravan</td>
<td>Kidnap done</td>
<td>Ram:I'll kill you</td>
<td><input type="checkbox" name="checks" id='two' value='test2' /> </td>
</tbody>
<p id="check"></p>
<button onclick="kro()">
Result
</button>
You define and concat to the variable wrong.
should be
var foo = ''; // declare outside of loop
for (var i=0; i<5; i++) {
foo += i + '\n' // concat to string
}
console.log(foo) //display it
Other way people would do it is with an array and joining it at the end
var foo = []; // declare outside of loop
for (var i=0; i<5; i++) {
foo.push(i) // add to array
}
console.log(foo.join('\n')) //display it by joining the array items

submit button not working when i combine my codes

it was working on when i split them into two but when i combine them the save button isnt working i tried changing the document.getElementById to document.getElementByClassName but it stops the function of both here is the code
<html>
<head>
<body>
<div class="container">
<table class="table table-hover table-bordered" id = "table1">
<thead>
<tr>
<th><center>Item Name</center> </th>
<th><center>Brand</center> </th>
<th><center>Selling Price</center> </th>
<th><center>Quantity</center> </th>
</tr>
</thead>
<tbody id = tbody1>
<tr>
<td>Cake</td>
<td>Pastry</td>
<td>100</td>
<td>5</td>
</tr>
<tr>
<td>Wat</td>
<td>But</td>
<td>100</td>
<td>5</td>
</tr>
</tbody>
</table>
</div>
<div class="container">
<table class="table table-hover table-bordered" id = "table2">
<thead>
<tr>
<th><center>Item Name</center> </th>
<th><center>Brand</center> </th>
<th><center>Selling Price</center> </th>
<th><center>Quantity</center> </th>
</tr>
</thead>
<tbody id = "myNewTableBody" class = "tbody2">
<tr class = "tr2">
</tr>
</tbody>
</table>
</div>
<input type = "submit" value = "save" name = "btnsave" onclick = "myFunction()" style = "position : absolute; top : 550px; left : 20px; font-size: 20px;"/></input>
</body>
<script>
var table = document.getElementsByTagName("table")[0];
var tbody = table.getElementsByTagName("tbody")[0];
tbody.onclick = function (e) {
e = e || window.event;
var data = [];
var target = e.srcElement || e.target;
while (target && target.nodeName !== "TR") {
target = target.parentNode;
}
if (target) {
var cells = target.getElementsByTagName("td");
for (var i = 0; i < cells.length; i++) {
data.push(cells[i].innerHTML);
}
}
var trnode = document.createElement("tr");
for(var i = 0; i < data.length; i++){
var tdnode = document.createElement("td");
var textnode = document.createTextNode(data[i]);
tdnode.appendChild(textnode);
trnode.appendChild(tdnode);
}
document.getElementById("myNewTableBody").appendChild(trnode);
};
function myFunction() {
var rows = document.getElementById("table2")
.getElementsByClassName("tbody2")
[0].getElementsByClassName("tr2").length;
var a = 1;
var b = 1;
for(var i = 0; i < rows; i++){
var x =
document.getElementById("table2").rows[a].cells.item(0).innerHTML
var y =
document.getElementById("table2").rows[a].cells.item(4).innerHTML
var a = a + 1;
var b = b + 1;
alert(x);
alert(y);
}
}
</script>
<html>
<head>
heres the seperate code of the save button that's working
<html>
<head>
<body>
<div class="container">
<table id = "table1">
<thead>
<tr>
<th><center>ID</center> </th>
<th><center>Item Name</center> </th>
<th><center>Category</center> </th>
<th><center>Selling Price</center> </th>
<th><center>Quantity</center> </th>
</tr>
</thead>
<tbody class = "tbody2">
<tr class = "tr2">
<td>1</td>
<td>Cake</td>
<td>Pastry</td>
<td>100</td>
<td>5</td>
</tr>
<tr class = "tr2">
<td>2</td>
<td>Bread</td>
<td>Pastry</td>
<td>5</td>
<td>100</td>
</tr>
</tbody>
</table>
</div>
<input type = "submit" value = "save" name = "btnsave"
onclick = "myFunction()" /></input>
</body>
<script>
function myFunction() {
var rows = document.getElementById("table1")
.getElementsByClassName("tbody2")[0]
.getElementsByClassName("tr2").length;
var a = 1;
var b = 1;
for(var i = 0; i < rows; i++){
var x = document.getElementById("table1").rows[a].cells.item(0).innerHTML
var y = document.getElementById("table1").rows[a].cells.item(4).innerHTML
var a = a + 1;
var b = b + 1;
alert(x);
alert(y);
}
}
</script>
</html>
In this code, second table, table with id table2 is empty. When you take, first column, in it's second row(table body), you get a null. Then you trying to access innerHTML property on a null element. Add some content to table2 and run check it again.
Again same problem comes when you say, document.getElementById("table2").rows[a].cells.item(4).innerHTML. Here you are trying to access 5th cell of a row, which contains only 4 cells.

Sorting multiple html tables with multiple sorts

I have several html tables on my page and I want to be able to sort them based on the value of one of their cell values. Here is an example of my tables
<div id="tables">
<table class="sortable">
<tr>
<td>Comic Book Name</td>
<td id="comic">Batman</td>
</tr>
<tr>
<td>Main Character</td >
<td ="character">Bruce Wayne</td>
</tr>
<tr>
<td>Hero Name</td>
<td id="hero">Batman</td>
</tr>
<tr>
<td>Published</td>
<td id="publish">05/01/1940</td>
</tr>
</table>
<table class="sortable">
<tr>
<td>Comic Book Name</td>
<td id="comic">Green Arrow</td>
</tr>
<tr>
<td>Main Character</td >
<td ="character">Oliver Queen</td>
</tr>
<tr>
<td>Hero Name</td>
<td id="hero">Green Arrow</td>
</tr>
<tr>
<td>Published</td>
<td id="publish">11/01/1941</td>
</tr>
</table>
</div>
I am providing the following drop down to allow users to filter.
<select id="OrderBy">
<option selected="selected" value="comic">Comic Name</option>
<option value="character">Character Name</option>
<option value="hero">Hero Name</option>
<option value="publish">Earliest Publish Date</option>
</select>
My hopes here are to sort the tables alphabetically by Comic book name when they choose Comic Name, alphabetically by Character Name when they select character name etc. etc.
Here is the javascript/jquery I have come up with so far. I'm sure this could be done better but I'm new to Javascript and Jquery.
$('#OrderBy').on('change', function () {
_order = $('#OrderBy').val();
switch (_order) {
case "comic":
$('#sortable').sort(function () {
});
break;
case "character":
$('#sortable').children().sort(function (a, b) {
});
break;
case "publish":
$('#sortable').sort(function () {
});
break;
case "publish":
$('#sortable').sort(function () {
if ($(b).children().find('#Hours').text() - $(a).children().find('#publish').text() <= 0) {
return $(a) - $(b);
}
return $(b) - $(a);
});
break;
}
});
Everywhere I look someone suggests Sorttables or tableSorter but I've only seen how they would work for a single table whose rows are being sorted. I know what everyone is thinking at this point, don't use tables this way. My problem is there is already a bunch of jquery and javascript supporting the tables and I'm not experienced enough in the languages to re-write all of that.
I like the idea of pushing everything onto a stack as described here but I always generated an error about how my array/stack was not defined.
First, you should not put several times the same id, but use classes instead:
<div id="tables">
<table class="sortable">
<tr>
<td>Comic Book Name</td>
<td class="comic">Green Arrow</td>
</tr>
<tr>
<td>Main Character</td >
<td class="character">Oliver Queen</td>
</tr>
<tr>
<td>Hero Name</td>
<td class="hero">Green Arrow</td>
</tr>
<tr>
<td>Published</td>
<td class="publish">11/01/1941</td>
</tr>
</table>
<table class="sortable">
<tr>
<td>Comic Book Name</td>
<td class="comic">Batman</td>
</tr>
<tr>
<td>Main Character</td >
<td class="character">Bruce Wayne</td>
</tr>
<tr>
<td>Hero Name</td>
<td class="hero">Batman</td>
</tr>
<tr>
<td>Published</td>
<td class="publish">05/01/1940</td>
</tr>
</table>
</div>
For your problem, I would use the native Array.prototype.sort method
var tables = [];
var $tables = $("table.sortable");
var container = $("#tables");
// this is the only specific case, as the date does not start by the year
// it will be used to sort by publish date
function sortByDate(a, b) {
return new Date(a.publish).getTime() - new Date(b.publish).getTime();
}
function sortTables(order) {
var sort;
if (order === "publish") {
tables = tables.sort(sortByDate);
} else {
tables = tables.sort(function(a, b) {
return a[order] < b[order] ? -1 : 1;
});
}
tables.forEach(function(data,i) {
tables[i].$el.detach()
container.append(tables[i].el);
});
}
function init() {
//populate the tables array that will be sorted
$tables.each(function(i, val) {
var $this = $(this);
tables.push({
$el: $this,
el: this,
comic: $this.find(".comic").text(),
character: $this.find(".character").text(),
hero: $this.find(".hero").text(),
publish: $this.find(".publish").text()
});
});
$("#OrderBy").on("change", function(event) {
sortTables(event.currentTarget.value);
});
//by default sort by Hero
sortTables("hero");
}
init();
Primarily, Sort can't happen when you have data in two different tables. To make it possible, you need to put id to them, not just classes because your primary issue isn't CSS. Again, if you put same id to different contents, it can't be spotted specifically. So, debugged code would be:
<div id="tables">
<table id="tbl1" class="sortable">
<tr>
<td>Comic Book Name</td>
<td class="comic">Batman</td>
</tr>
<tr>
<td>Main Character</td >
<td class="character">Bruce Wayne</td>
</tr>
<tr>
<td>Hero Name</td>
<td class="hero">Batman</td>
</tr>
<tr>
<td>Published</td>
<td class="publish">05/01/1940</td>
</tr>
</table>
<table id="tbl2" class="sortable">
<tr>
<td>Comic Book Name</td>
<td class="comic">Green Arrow</td>
</tr>
<tr>
<td>Main Character</td >
<td class="character">Oliver Queen</td>
</tr>
<tr>
<td>Hero Name</td>
<td class="hero">Green Arrow</td>
</tr>
<tr>
<td>Published</td>
<td class="publish">11/01/1941</td>
</tr>
</table>
Your drop-down menu(filter box) is properly defined. Now, in js code, there are some syntactical mistakes.
like, 'class' identifier is '.', 'id' identifier is '#', you used '#' instead of '.' some places :
switch (_order) {
case "comic":
$('#sortable').sort(function () {});
debugged code would be:
$('#OrderBy').on('change', function () {
_order = $('#OrderBy').val();
switch (_order) {
case "comic":
$('.sortable').sort(function () {});
break;
case "character":
$('.sortable').children().sort(function (a, b) {
});
break;
case "publish":
$('.sortable').sort(function () {
});
break;
case "publish":
$('.sortable').sort(function () {
if ($(b).children().find('#Hours').text() - $(a).children().find('#publish').text() <= 0) {
return $(a) - $(b);
}
return $(b) - $(a);
});
break;
}});
There's no official table sort() function jquery library. It would work for array only, but you won't have any array here.
So we make a sort function on our own. We can name it 'sortTable()'. The code for this should be:
<!-- -------------------------------------------------------------- -->
<!-- Secondary functions -->
<!-- Creates a new table to display the sorted Table -->
function createEmptyTable(){
var outerDiv = document.createElement('div');
outerDiv.setAttribute('id','ResultTable');
var innerTable = doucment.createElement('table');
innerTable.setAttribute('id','sortedTable');
var newRows = new Array();
var recordIndex = document.getElementsByClassName('comic');
innerTable.innerHTML = "<tr> <th>Comic Book Name </th> <th>Main Character</th> <th>Hero Name</th> <th>Published</th> </tr>";
for(var i=0; i<recordIndex.Length;i++){
newRows[i]= document.createElement('tr');
outerDiv.appendChild(innerTable).appendChild(newRows[i]);
}
}
<!-- ------------------------------------------------------------- -->
<!-- function to find out in which table chosen filter belongs -->
function recordSearch(keyWord){
var sortableTables = document.getElementsByClassName('sortable');
for( var i=0; i<sortableTables.length;i++){
if($(sortableTables[i]).find(keyword)){
return sortableTable[i];
}
}
<!-- ------------------------------------------------------------- -->
<!-- Primary function to sort the Table -->
function sortTable(filtered_option){
<!-- first we delete any existing sorted table -->
if(document.getElementById('ResultTable')){
var existingSortedTable = document.getElementbyId('ResultTable');
existingSortedTable.removeChild(document.getElementById('sortedTable');
}
<!-- now we create new table & put the result -->
createEmptyTable();
var comicNames = document.getElementsByClassName('comic');
var characterNames = document.getElementsByClassName('character');
var heroNames = document.getElementsByClassName('hero');
var publishDates = document.getElementsByClassName('publish');
switch (filtered_option) {
case 'comic' :
var sortedComicNames = comicNames.sort();
for(var i=0;i<sortedComicNames.length;i++){
var foundRecord = recordSearch(sortedComicNames[i]);
var allFields = foundRecord.getElementByTagName('tr').getElementsByClassName('td');
var emptyRows = document.getElementById('sortedTable').getElementsByTagName('tr');
for(var j=0;j<allFields.length;j++){
emptyRows[i+1].innerHTML = "<td>" + allFields[j].value + "</td>" ;
}}
break;
case 'character' :
var sortedCharacterNames= characterNames.sort();
for(var i=0;i<characterNames.length;i++){
var foundRecord = recordSearch(sortedCharacterNames[i]);
var allFields = foundRecord.getElementByTagName('tr').getElementsByClassName('td');
var emptyRows = document.getElementById('sortedTable').getElementsByTagName('tr');
for(var j=0;j<allFields.length;j++){
emptyRows[i+1].innerHTML = "<td>" + allFields[j].value + "</td>" ;
}}
break;
case 'hero' :
var sortedHeroNames= heroNames.sort();
for(var i=0;i<heroNames.length;i++){
var foundRecord = recordSearch(heroNames[i]);
var allFields = foundRecord.getElementByTagName('tr').getElementsByClassName('td');
var emptyRows = document.getElementById('sortedTable').getElementsByTagName('tr');
for(var j=0;j<allFields.length;j++){
emptyRows[i+1].innerHTML = "<td>" + allFields[j].value + "</td>" ;
}}
break;
case 'publish' :
var sortedPublishedDates= publishedDates.sort();
for(var i=0;i<publishedDates.length;i++){
var foundRecord = recordSearch(publishedDates[i]);
var allFields = foundRecord.getElementByTagName('tr').getElementsByClassName('td');
var emptyRows = document.getElementById('sortedTable').getElementsByTagName('tr');
for(var j=0;j<allFields.length;j++){
emptyRows[i+1].innerHTML = "<td>" + allFields[j].value + "</td>" ;
}}
break;
}
}
<!-- -------------------------------------------------------------------- -->
Put them together and Try. Let me know if it works.

Categories