How to create and increment a number without the table length - javascript

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! :)

Related

How to fix data table data is being updated or destroy table?

I am trying to create a data table with my dataset and I want to reinitialize the same table for the new data. But it's getting appended to the same table rather than re-initialising it. This is my code
function showTab(name,data){
trheader = "";
trvalues = "";
trcontent = "";
trfoot = "";
table_id = "";
trheader += "<thead>";
for (i = 0; i < data[0].length; i++){
trheader += "<th>" + data[0][i]+ "</th>";
}
trheader += "</thead>";
if(data[1].length > 0){
for (i = 0; i < data[1].length; i++){
trvalues += "<tbody>"
trvalues += "<tr>"
trvalues += "<td class='center'>" + (i + 1) + "</td>";
trvalues += "<td class='center'>" + data[1][i][0] + "</td>";
for (j = 0; j < 4; j++ ){
trvalues += "<td class='center'>" + data[1][i][1][j].toLocaleString() + "</td>";
}
for(j = 4; j < 7; j++){
var patt = /^-/;
var color = data[1][i][1][j].toString();
if (color.match(patt)){
trvalues += "<td class='center redCell'>" + data[1][i][1][j].toFixed(2) + '%'+ "</td>";
}
else if(color == '0'){
trvalues += "<td></td>"
}
else{
trvalues += "<td class='center greenCell'>" + data[1][i][1][j].toFixed(2) + '%' + "</td>";
}
}
trvalues += "</tr>"
trvalues += "</tbody>"
}
}
if (data[2].length > 0)
{
trfoot += "<tfoot>"
trfoot += "<tr>"
trfoot += "<td></td>"
trfoot += "<td>Total</td>"
for (i = 0; i < 4; i++){
trfoot += "<td class='center'>" + data[2][i].toLocaleString() + "</td>";
}
for( i = 4; i < 7; i ++){
var patt = /^-/;
var color = data[2][i].toString();
if (color.match(patt)){
trfoot += "<td class='center redCell'>" + data[2][i].toFixed(2) + '%'+ "</td>";
}
else if(color == '0'){
trfoot += "<td></td>"
}
else{
trfoot += "<td class='center greenCell'>" + data[2][i].toFixed(2) + '%' + "</td>";
}
}
trfoot += "</tr>"
trfoot += "</tfoot>"
}
trcontent = trheader + trvalues + trfoot;
table = "#"+name;
$(table).html(trcontent);
$(table).DataTable({
"scrollY": "400px",
"scrollCollapse": true,
"paging": false,
"searching": false,
"destroy": true
});
// new addition code
var seen = {};
$('table tr').each(function() {
var txt = $(this).text();
if (seen[txt])
$(this).remove();
else
seen[txt] = true;
});
If I use $(table).html it will only load the last value that is trfooter. I have tried setting bDestroy for the table but nothing helps. Please help. Thanks.
This is my table skeleton
<table border = "1px"cellpadding="0" cellspacing="1" width="100%" id= <%= table&.table_name %> style="background: none repeat scroll 0% 0%;font-size:12px;">
</table>
You can destroy and re-declare your datatable to load the latest content
// First Declaration
var table = $('#myTable').DataTable();
$('#submit').on( 'click', function () {
$.getJSON( 'newTable', null, function ( json ) {
// Destroy
table.destroy();
$('#myTable').empty(); // empty in case the columns change
// ReDraw
table = $('#myTable').DataTable( {
columns: json.columns,
data: json.rows
} );
} );
} );
For more reference : https://datatables.net/reference/api/destroy()

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>

How do I add different classes to <td> in Javascript

Hey I have two td elements in a table.
I want the have separate style classes for them. How do I do this?
This is my code:
table += "<tr>";
for(var i = 0; i < data.list.length; i++){
table += "<td>" + "<table>" + "<td>" + value1 "</td>" + "<td>" + value2 + "</td>" + "</table>";
}
table += "</tr>";
I have tried to simply add class in td element but that does not work.
Any ideas? I use Javascript to create the table.
So this does not work:
table += "<tr>";
for(var i = 0; i < data.list.length; i++){
table += "<td>" + "<table>" + "<td class="one">" + value1 "</td>" + "<td class="two">" + value2 + "</td>" + "</table>";
}
table += "</tr>";
You should be using single quotes inside double-quoted strings, like this
table += "<tr>";
for(var i = 0; i < data.list.length; i++){
table += "<td>" + "<table>" + "<td class='one'>" + value1 "</td>" + "<td class='two'>" + value2 + "</td>" + "</table>";
}
table += "</tr>";

JavaScript-How to make Html Table editable

I have a function of creating table from a .csv file using JavaScript. I want to make the last column of the table editable. Part of that function where table is being generated is
for (var i = 0; i < CSVLines.length; i++) {
OutputTableRows += "<tr>";
var CSVValues = CSVLines[i].split(",");
for (var j = 0; j < CSVValues.length; j++) {
OutputTableRows += "<td>" + "<p>" + CSVValues[j] + "<p>" + "</td>";
}
OutputTableRows += "</tr>";
}
I have tried
OutputTableRows += "<td>" + "<p contenteditable="true">" + CSVValues[j] + "<p>" + "</td>";
but it's not working
I think you should say in your inner loop:-
if(j == CSVValues.length-1){
tableRow = '<td><input type="text" value="VALUE"/></td>';
tableRow = tableRow.replace('VALUE',CSVValues[j]);
OutputTableRows += tableRow;
}
else{
OutputTableRows += "<td>" + "<p>" + CSVValues[j] + "<p>" + "</td>";
}
I'd suggest, at first glance:
OutputTableRows += "<td>" + "<p" + (j === (CSVValues.length - 1) ? " contentEditable" : "") + ">" + CSVValues[j] + "</p>" +"</td>";
The relevant part, of course, is:
"<p" + (j === (CSVValues.length - 1) ? " contentEditable" : "") + ">"
If j is equal to the length of CSVValues minus 1, then it's reasonable to assume that this must be the last iteration of that for loop, and therefore this is the row that should have the contentEditable attribute, otherwise it should not (and must be an earlier iteration of the loop).
Also, note the changed </p> (from your original <p>), which closes the already-open <p>, as opposed to creating a new, sibling, paragraph element.
References:
Conditional ('ternary') operator.
contentEditable attribute.

Javascript inserting data into HTML table

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.

Categories

Resources