Javascript inserting data into HTML table - javascript

This is a rather simple question, I am having problems inserting data from Javascript into an HTML table.
Here is an excerpt of my JavaScript:
UPDATED - I got rid of the two loops and simplified it into one, however there is still a problem..
for (index = 0; index < enteredStrings.length; index++) {
output.innerHTML += "<td>" + enteredStrings[index] + "</td>"
+ "<td>" + enteredStringsTwo[index] + "</td>";
nameCounter++;
total.innerHTML = "Total: " + nameCounter;
}
And here is an except of my HTML page:
<table id="nameTable">
<tr>
<th>First</th><th>Last</th>
</tr>
Updated Picture:

Try this (edited):
var tableContent = '<tr>';
for (index = 0; index < enteredStrings.length; index++) {
tableContent += "<td>" + enteredStrings[index] + "</td>";
nameCounter++; // I don't know if this should be there,
// logically the counter should be incremented here as well?
total.innerHTML = "Total: " + nameCounter;
}
tableContent += '</tr><tr>';
for (index = 0; index < enteredStringsTwo.length; index++) {
tableContent += "<td>" + enteredStringsTwo[index] + "</td>";
nameCounter++;
total.innerHTML = "Total: " + nameCounter;
}
tableContent += '</tr>';
output.innerHTML += tableContent;
Edit2 (for updated question code):
var tableContent = '<tr>';
for (index = 0; index < enteredStrings.length; index++) {
tableContent += "<td>" + enteredStrings[index] + "</td>"
+ "<td>" + enteredStringsTwo[index] + "</td>";
nameCounter++;
total.innerHTML = "Total: " + nameCounter;
}
tableContent += '</tr>';
output.innerHTML += tableContent;
Edit3 (after looking at the code sent in email):
var tableContent = "";
for (index = 0; index < enteredStrings.length; index++) {
tableContent += "<tr><td>" + enteredStrings[index] + "</td>"
+ "<td>" + enteredStringsTwo[index] + "</td></tr>";
nameCounter++;
total.innerHTML = "Total: " + nameCounter;
}
output.innerHTML = tableContent;

instead of closing the td you are opening new ones
try
for (index = 0; index < enteredStrings.length; index++) {
output.innerHTML += "<td>" + enteredStrings[index] + "</td>";
total.innerHTML = "Total: " + nameCounter;
}
for (index = 0; index < enteredStringsTwo.length; index++) {
output.innerHTML += "<td>" + enteredStringsTwo[index] + "</td>";
nameCounter++;
total.innerHTML = "Total: " + nameCounter;
}
UPDATE:
you are appending the html to the table instead of the row.
in this case, the browser created a row for you automatically after the each td is appended.

With slight modifications in your code,
var outputTbl = document.getElementById('nameTable');
var output = document.createElement("tr");
outputTbl.appendChild(output);
for (index = 0; index < enteredStrings.length; index++) {
output.innerHTML += "<td>" + enteredStrings[index] + "</td>";
total.innerHTML = "Total: " + nameCounter;
}
for (index = 0; index < enteredStringsTwo.length; index++) {
output.innerHTML += "<td>" + enteredStringsTwo[index] + "</td>";
nameCounter++;
total.innerHTML = "Total: " + nameCounter;
}

If you need to add inner html code here.
<table id="nameTable" style="width:300px;">
<tr>
<th>First</th><th>Last</th>
</tr>
</table>
You can use Jnerator in this case.
If this is your data:
var data = [
{ first: 'Cole', last: 'Alan'},
{ first: 'Michael', last: 'Scott'}
]
You can add them to you table in next way:
for(var i=0; i<data.length; i++) {
var item = data[i];
var row = $j.tr({ child:[$j.td(item.first), $j.td(item.last)] });
nameTable.appendChild(row.dom());
}
nameTotal.innerHTML = 'Total: ' + data.length;
This is example.

Related

how can i alternate row class after api data

I have tried everything i know and can't get an alterate tablerow class to work , without having all the rows duplicated or having a bunch of dummy rows inserted
Here is what i have
<script>
fetch("https://www63.myfantasyleague.com/2021/export?TYPE=league&L=43570&JSON=1").then(
res => {
res.json().then(
data => {
console.log(data.league.franchises.franchise);
if (data.league.franchises.franchise.length > 0) {
var temp = "";
temp += "<table id='league_emails'>";
temp += "<tbody>";
temp += "<tr><th>Franchise</th><th>Owner Name</th><th>Email</th></tr>";
data.league.franchises.franchise.forEach((itemData) => {
for (var i = 0; i < data.league.franchises.franchise.length; i++) {
if (i % 2)
temp += '<tr class="eventablerow">';
else
temp += '<tr class="oddtablerow">';
}
temp += "<td>" + itemData.name + "</td>";
temp += "<td>" + itemData.owner_name + "</td>";
temp += "<td>" + itemData.email + "</td>";
});
temp += "</tbody>";
temp += "</table>";
document.getElementsByClassName('commish_league_safe')[0].innerHTML = temp;
}
}
)
}
)
</script>
<div class="commish_league_safe"></div>
The issue lays here and i have tried a dozen things and wrapped it different ways
for (var i = 0; i < data.league.franchises.franchise.length; i++) {
if (i % 2)
temp += '<tr class="eventablerow">';
else
temp += '<tr class="oddtablerow">';
}
<script>
fetch(https://www63.myfantasyleague.com/2021/export?TYPE=league&L=43570&JSON=1).then(
res => {
res.json().then(
data => {
console.log(data.league.franchises.franchise);
if (data.league.franchises.franchise.length > 0) {
var temp = "";
temp += "<table id='league_emails'>";
temp += "<tbody>";
temp += "<tr><th>Franchise</th><th>Owner Name</th><th>Email</th></tr>";
data.league.franchises.franchise.forEach((itemData,i) => {
/* for (var i = 0; i < data.league.franchises.franchise.length; i++) { */
if (i % 2)
temp += '<tr class="eventablerow">';
else
temp += '<tr class="oddtablerow">';
/* } */
temp += "<td>" + itemData.name + "</td>";
temp += "<td>" + itemData.owner_name + "</td>";
temp += "<td>" + itemData.email + "</td>";
temp += "</tr>";
});
temp += "</tbody>";
temp += "</table>";
document.getElementsByClassName('commish_league_safe')[0].innerHTML = temp;
}
}
)
}
)
</script>
<div class="commish_league_safe"></div>
Just before ending the loop close the tr tag.
temp += "" + itemData.email + ""; after this line just add closing tag to append that to temp variable.

Trying to call a function using onclick

I have created a function to create a table and have populated it with questions. I have tried to create a button to bring the table but it seems to not be working. Anyone know what I have missed?
<body>
<button onclick="createSheet()">Display</button>
</body>
<script>
var totalQuestions;
function createSheet() {
var sheet = "";
totalQuestions = 8;
sheet += "<div><table>";
for (var i = 0; i < totalQuestions; i++) {
sheet += "<tr>";
sheet += "<td class='question'>";
sheet += "<div class='questionNumber'>" + "A" + (i + 1) + "</div>";
sheet += "<div class='qContent'>" + addition2() + " </div>";
sheet += "</td>";
sheet += "<td class='question'>";
sheet += "<div class='questionNumber'>" + "B" + (i + 1) + "</div>";
sheet += "<div class='qContent'>" + addition2() + " </div>";
sheet += "</td>";
sheet += "<td class='question'>";
sheet += "<div class='questionNumber'>" + "C" + (i + 1) + "</div>";
sheet += "<div class='qContent'>" + addition2() + " </div>";
sheet += "</td>";
sheet += "</tr>";
}
return sheet;
sheet += "</table></div>";
}
function addition2() {
var difficulty = 1000;
var ans;
for (var i = 0; i < totalQuestions; i++) {
var numGen = Math.round(Math.random() * difficulty + 100);
var numGen1 = Math.round(Math.random() * difficulty + 100);
var question = numGen + " + " + numGen1
var ans = numGen + numGen1
}
return question;
}
</script>
I suppose what you are trying to do is display a table when the button is clicked:
<body>
<button onclick="createSheet()">Display</button>
<div id="tableContainer">
</div>
</body>
<script>
var totalQuestions;
function createSheet() {
var sheet = "";
totalQuestions = 8;
sheet += "<div><table>";
for (var i = 0; i < totalQuestions; i++) {
sheet += "<tr>";
sheet += "<td class='question'>";
sheet += "<div class='questionNumber'>" + "A" + (i + 1) + "</div>";
sheet += "<div class='qContent'>" + addition2() + " </div>";
sheet += "</td>";
sheet += "<td class='question'>";
sheet += "<div class='questionNumber'>" + "B" + (i + 1) + "</div>";
sheet += "<div class='qContent'>" + addition2() + " </div>";
sheet += "</td>";
sheet += "<td class='question'>";
sheet += "<div class='questionNumber'>" + "C" + (i + 1) + "</div>";
sheet += "<div class='qContent'>" + addition2() + " </div>";
sheet += "</td>";
sheet += "</tr>";
}
// return sheet; !! return over here will stop the function from continuing
sheet += "</table></div>";
document.getElementById("tableContainer).innerHtml = sheet;
}
function addition2() {
var difficulty = 1000;
var ans;
for (var i = 0; i < totalQuestions; i++) {
var numGen = Math.round(Math.random() * difficulty + 100);
var numGen1 = Math.round(Math.random() * difficulty + 100);
var question = numGen + " + " + numGen1
var ans = numGen + numGen1
}
return question;
}
</script>

How to get the specific item from array on click in javascript table created using javascript

My code is this
var html = "<table>";
for (var i = 0; i < data.length; i++) {
html += "<tr>";
html += "<td>" + data[i].personName + "</td>";
html += "<td>" + data[i].fatherName + "</td>";
html += "<td>" + data[i].personPhone + "</td>";
html += "<td>" + data[i].personCnic + "</td>";
html += "<td>" + data[i].deliveryDate + "</td>";
html += "<td>" + data[i].submissionDate + "</td>";
html += "<td>" + data[i].year + "</td>";
html += "<td>" + data[i].session + "</td>";
html += "<td>" + data[i].board + "</td>";
html += "<td>" + data[i].amount + "</td>";
html += "</tr>";
}
html += "</table>";
document.getElementById("box").innerHTML = html;
How can I use an event listeners using this approach?
I have seen many methods but none of that match my scenario.
You need to add an onClick which is different for every row, in there you pass as parameter the row index :) than you can handle it on the function.
var html = "<table>";
for (var i = 0; i < data.length; i++) {
html+="<tr onclick='myFunction("+i+")'>";
html+="<td>"+data[i].personName+"</td>";
html+="<td>"+data[i].fatherName+"</td>";
html+="<td>"+data[i].personPhone+"</td>";
html+="<td>"+data[i].personCnic+"</td>";
html+="<td>"+data[i].deliveryDate+"</td>";
html+="<td>"+data[i].submissionDate+"</td>";
html+="<td>"+data[i].year+"</td>";
html+="<td>"+data[i].session+"</td>";
html+="<td>"+data[i].board+"</td>";
html+="<td>"+data[i].amount+"</td>";
html+="</tr>";
}
html+="</table>";
function myFunction(x) {
console.log('index' + x + 'was clicked')
// do the handling here
}
HERE YOU HAVE YOUR DEMO
let data = [{ personName: "test1"}, {personName: "test2"}]
var html = "<table>";
for (var i = 0; i < data.length; i++) {
html+="<tr onclick='myFunction("+i+")'>";
html+="<td>"+data[i].personName+"</td>";
html+="</tr>";
}
html+="</table>";
document.getElementById("demo").innerHTML = html;
function myFunction(i) {
console.log('index ' + i + ' was clicked')
// do the handling here
console.log(data[i])
}
<p id="demo"></p>
You can add the event listeners after you adding their html into the DOM.
Like this:
document.getElementById("box").querySelectorAll('tr').forEach(tr => {
tr.addEventListener('click', function() {
console.log(tr.textContent);
});
});
And working demo: (I added some dumb data so the demo will work)
const data = new Array(5).fill(0).map((_, idx) => ({
personName: `personName-${idx}`,
fatherName: `fatherName-${idx}`,
personPhone: `personPhone-${idx}`,
personCnic: `personCnic-${idx}`,
deliveryDate: `deliveryDate-${idx}`,
submissionDate: `submissionDate-${idx}`,
year: `year-${idx}`,
session: `session-${idx}`,
board: `board-${idx}`,
amount: `amount-${idx}`
}));
var html = "<table>";
for (var i = 0; i < data.length; i++) {
html += "<tr>";
html += "<td>" + data[i].personName + "</td>";
html += "<td>" + data[i].fatherName + "</td>";
html += "<td>" + data[i].personPhone + "</td>";
html += "<td>" + data[i].personCnic + "</td>";
html += "<td>" + data[i].deliveryDate + "</td>";
html += "<td>" + data[i].submissionDate + "</td>";
html += "<td>" + data[i].year + "</td>";
html += "<td>" + data[i].session + "</td>";
html += "<td>" + data[i].board + "</td>";
html += "<td>" + data[i].amount + "</td>";
html += "</tr>";
}
html += "</table>";
const box = document.getElementById("box");
box.innerHTML = html;
box.querySelectorAll('tr').forEach(tr => {
const _tr = tr;
tr.addEventListener('click', () => {
console.log(_tr.textContent);
});
});
<div id="box"></div>

Dynamic option list from an array

I have the following code which works perfectly, but can I make the drop menu dynamic using quantityAllowed as the maximum the drop menu goes to. at the moment I have added 10 options for every print, but what i would prefer is the drop menus only have the correct quantity in. I think the loop I need would go where the options begin using the value of the loop, but when i have tried, i just get an error, so I know I have done something wrong.
function arrayData() {
var index;
var text = "<ul>";
var htmlTable = '';
var calcTable = [];
calcTable = [
{ printName:"Name1", printPrice:8000000, quantityAllowed:6},
{ printName:"Name2", printPrice:12000000, quantityAllowed:5},
{ printName:"Name3", printPrice:20000000, quantityAllowed:4},
{ printName:"Name4", printPrice:2000000, quantityAllowed:3},
];//end of array
for (index = 0; index < calcTable.length; index++) {
var myclass = 'class="printwant"';
$("#tbNames tr:last").after("<tr>" +
"<td style='padding:0px 0px 0px 36px;'>" + calcTable[index].printName + "</td>" +
"<td class='printpoints'>" + calcTable[index].printPrice + "</td>" +
"<td>" + calcTable[index].quantityAllowed + "</td>" +
"<td><select " + myclass + "><option value=0>0</option><option value=1>1</option><option value=2>2</option><option value=3>3</option><option value=4>4</option><option value=5>5</option><option value=6>6</option><option value=7>7</option><option value=8>8</option><option value=9>9</option><option value=10>10</option></select></td><td></td> </tr>");
}//end of loop
$("#tbNames tr:last").after("<tr>" + "<td colspan = '5' height=40 > </tr>");
}
You can separate out your HTML generation code from the jQuery DOM assignment. This makes it a little easier to read and manipulate. When you come to your select/option area, drop it into a for... loop to generate the appropriate number of options.
function arrayData() {
var index;
var text = "<ul>";
var htmlTable = '';
var calcTable = [];
calcTable = [
{ printName:"Name1", printPrice:8000000, quantityAllowed:6},
{ printName:"Name2", printPrice:12000000, quantityAllowed:5},
{ printName:"Name3", printPrice:20000000, quantityAllowed:4},
{ printName:"Name4", printPrice:2000000, quantityAllowed:3},
];//end of array
for (index = 0; index < calcTable.length; index++) {
var myclass = 'class="printwant"';
var output = '';
output += "<tr>";
output += "<td style='padding:0px 0px 0px 36px;'>" + calcTable[index].printName + "</td>";
output += "<td class='printpoints'>" + calcTable[index].printPrice + "</td>";
output += "<td>" + calcTable[index].quantityAllowed + "</td>";
output += "<td><select " + myclass + ">";
for( var i=0, x=calcTable[index].quantityAllowed; i<x; i++ ){
output += '<option value="' + i + '">' + i + '</option>';
}
output += "</select></td><td></td> </tr>";
$("#tbNames tr:last").after(output);
}//end of loop
$("#tbNames tr:last").after("<tr>" + "<td colspan = '5' height=40 > </tr>");
}
arrayData();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="tbNames">
<tr></tr>
<tr></tr>
</table>

How to create and increment a number without the table length

I want to increment a number in the 1st column of each row of my table.
I want to make it without knowing the length of the data.
I tried this, and the number doesn't increment, but just display the variable value in each rows.
$(document).ready(function (e) {
if ($("#checker").val() == "ka") {
var data = $("#report_all").serialize();
$('#all_report thead').empty();
$('#all_report tbody').empty();
$.ajax({
data: data,
type: "Post",
url: "../php/report/report_all_KA.php",
success: function (data) {
var list = JSON.parse(data);
for (var x = 0; i < list.length; i++) {
var n = 1;
n = list.length++;
}
var th = "";
th += "<th>" + "<center>" + 'no' + "</center>" + "</th>";
th += "<th>" + "<center>" + 'Tanggal' + "</center>" + "</th>";
th += "<th>" + "<center>" + 'Type Kadar Air' + "</center>" + "</th>";
th += "<th>" + "<center>" + 'Kode Material' + "</center>" + "</th>";
th += "<th>" + "<center>" + 'Nama Material' + "</center>" + "</th>";
th += "<th>" + "<center>" + 'Storage Location' + "</center>" + "</th>";
th += "<th>" + "<center>" + 'Kadar Air' + "</center>" + "</th>";
th += "<th>" + "<center>" + 'Nama PPIC' + "</center>" + "</th>";
th += "</th>";
$("#all_report thead").append(th);
for (var i = 0; i < list.length; i++) {
var tr = "<tr>";
tr += "<td>" + n + "</td>";
tr += "<td>" + list[i]['date'] + "</td>";
tr += "<td>" + list[i]['type'] + "</td>";
tr += "<td>" + list[i]['kode'] + "</td>";
tr += "<td>" + list[i]['nama'] + "</td>";
tr += "<td>" + list[i]['sloc'] + "</td>";
tr += "<td>" + list[i]['ka'] + "</td>";
tr += "<td>" + list[i]['ppic'] + "</td>";
tr += "</tr>";
$("#all_report tbody").append(tr);
$("#all_report").show();
}
return false;
}
});
//[...]
The code that I made for the increment in the whole code above is like this.
for(var x = 0; i < list.length; i++){
var n=1;
n= list.length++;
}
If you are just looking for a column in your table that corresponds to the row numbers, you can replace "<td>" +n+"</td>" with "<td>"+(i+1)+"</td>".
Then you won't even need that other loop!
var table = document.getElementsByTagName('table')[0],
rows = table.getElementsByTagName('tr'),
text = 'textContent' in document ? 'textContent' : 'innerText';
for (var i = 0, len = rows.length; i < len; i++) {
rows[i].children[0][text] = i + rows[i].children[0][text];
}
Hope it works! :)

Categories

Resources