Minervaz Mine Minervaz Mine - 30 days ago 8
Javascript Question

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

Answer Source

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!