Javascript - add multiples rows in html table - javascript

This question can be a duplicate.
I need add 24 rows in a html table with 8 columns on click of button. I look for some examples, and I tried this (code below), but only row is add. Someone could help? Thanks for attention.
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = 3;
for (var i = 0; i < 24; i++) {
var row = table.insertRow(rowCount);
var cell1 = row.insertCell(i);
var element1 = document.createElement("input");
element1.type = "checkbox";
element1.name="chbx";
var element2 = document.createElement("label");
if (i < 9) {
element2.innerHTML = "0" + i ;
}
else {
element2.innerHTML = i;
}
element2.name="lbl";
cell1.appendChild(element1);
cell1.appendChild(element2);
var cell2 = row.insertCell(i + 1);
cell2.innerHTML = "2";
var cell3 = row.insertCell(i + 2);
cell3.innerHTML = "3";
var cell4 = row.insertCell(i + 3);
cell4.innerHTML = "4";
var cell5 = row.insertCell(i + 4);
cell5.innerHTML = "5";
var cell6 = row.insertCell(i + 5);
cell6.innerHTML = "6";
var cell7 = row.insertCell(i + 6);
cell7.innerHTML = "7";
var cell8 = row.insertCell(i + 7);
cell8.innerHTML = "8";
rowCount++;
}
}

Check out this approach:
JS
var table = document.getElementById('table');
function addRows(table, rows, columns){
var row = '';
for (var i = 0; i < rows; i++){
row = '<tr>';
for(var j = 0; j < columns; j++){
row += '<td>' + j +'</td>'
}
row += '</tr>';
table.innerHTML += row
}
}
addRows(table, 24, 8);
HTML
<table id="table">
</table>
Check out this codepen.

Related

Get the record id of a dynamically populated table in JavaScript

I have added records to a table that contains values in two text boxes and a button per each row. How can I get the record number of a particular button clicked by the user?
<table id="myTable">
</table>
<script>
var table=document.getElementById("myTable");
var i=0;
for(i; i<3; i++)
{
var row = table.insertRow(i);
var cell0=row.insertCell(0);
var element0=document.createElement("input");
element0.type="text";
element0.value = "Hello : " + i;
cell0.appendChild(element0);
var cell1=row.insertCell(1);
var element1=document.createElement("input");
element1.type="text";
element1.value = "Welcome : " + i*2;
cell1.appendChild(element1);
var cell2=row.insertCell(2);
var element2=document.createElement("input");
element2.type="button";
element2.value = "Clcik : " + i*i;
element2.onclick = function show_id() { alert("Record ID"); }
cell2.appendChild(element2);
}
</script>
Why can't you use an index for tracking the record?
Hoping this is the use case you are looking for. Include more details in case you need anything other than this.
<table id="myTable">
</table>
<script>
var table=document.getElementById("myTable");
var i=0;
for(i; i<3; i++)
{
const recordId = i+1;
var row = table.insertRow(i);
var cell0=row.insertCell(0);
var element0=document.createElement("input");
element0.type="text";
element0.value = "Hello : " + i;
cell0.appendChild(element0);
var cell1=row.insertCell(1);
var element1=document.createElement("input");
element1.type="text";
element1.value = "Welcome : " + i*2;
cell1.appendChild(element1);
var cell2=row.insertCell(2);
var element2=document.createElement("input");
element2.type="button";
element2.value = "Clcik : " + i*i;
element2.onclick = function show_id() {
alert("Record ID - " + recordId);
}
cell2.appendChild(element2);
}
</script>

Converting CSV input in textarea to dynamic table

This picture defines what I need
I want that the data I enter dynamically to be converted to table with each comma defining the column and the newline defining the new row.
Below is the code I have tried. Can I have a better approach to this problem?
<script>
function myFunction()
{
var x = document.getElementById("textarea").value.split(" ");
var customers = new Array();
customers.push(x[0]);
customers.push(x[1]);
customers.push(x[2]);
var table = document.createElement("TABLE");
table.border = "1";
//Get the count of columns.
var columnCount = customers[0].length;
//Add the header row.
var row = table.insertRow(-1);
for (var i = 0; i < columnCount; i++) {
var headerCell = document.createElement("TH");
headerCell.innerHTML = customers[0][i];
row.appendChild(headerCell);
}
//Add the data rows.
for (var i = 1; i < customers.length; i++) {
row = table.insertRow(-1);
for (var j = 0; j < columnCount; j++) {
var cell = row.insertCell(-1);
cell.innerHTML = customers[i][j];
}
}
var dvTable = document.getElementById("dvTable");
dvTable.innerHTML = "";
dvTable.appendChild(table);
}
</script>
<html>
<head>
<title>Player Details</title>
</head>
<body align = "center">
<h3 align = "center"><b>Input CSV</b></h3>
<p align = "center"><textarea rows="10" cols="50" name = "csv" id = "textarea"></textarea></p><br>
<button type="button" id = "convert" onclick="myFunction()">Convert</button><br>
<br>
<div id = "team"></div>
</body>
</html>
You need to split the data first using newline (\n) and then using comma (,) character.
The table can be created as string and finally inserted to the correct div.
Refer the code below to get you started.
function myFunction() {
var tbl = "<table class='table table-responsive table-bordered table-striped'><tbody>"
var lines = document.getElementById("textarea").value.split("\n");
for (var i = 0; i < lines.length; i++) {
tbl = tbl + "<tr>"
var items = lines[i].split(",");
for (var j = 0; j < items.length; j++) {
tbl = tbl + "<td>" + items[j] + "</td>";
}
tbl = tbl + "</tr>";
}
tbl = tbl + "</tbody></table>";
var divTable = document.getElementById('team');
console.log(tbl);
divTable.innerHTML = tbl;
}
I've used bootstrap for css, you may want to use your own (or not).
Refer jsFiddle here.

li items inside table

Is it possible to place the output of below code in table? The reason is that I want to put headings and nice alignment between firstname and lastname.
Javascript
var nameList = document.getElementById('names');
namearray.push([firstname, lastname]);
namearray.sort();
for(var i = 0; i < namearray.length; i++){
letters += '<li>' + firstname[i] + " " + lastname[i]+ '</li>';
nameList.innerHTML = letters;
}
HTML
<ul id="names">
var nameList = document.getElementById('names');
namearray.push([firstname, lastname]);
namearray.sort();
for(var i = 0; i < namearray.length; i++){
var row = nameList.insertRow(i);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
cell1.innerHTML = firstname[i];
cell2.innerHTML = lastname[i];
}
HTML:
<table id="names"></table>

increment Calendar date in javascript

I am writing code to add rows dynamically on selecting the month and year. It should display rows of labels with all dates for that month.
I have written code for adding new row on button click and am stuck on adding date to label dynamically
<BODY>
<INPUT type="button" value="Add Row" id="addRow" onclick="addRow('dataTable')" />
<TABLE id="dataTable" width="350px" border="1">
</TABLE>
<%
int year= 2015,month = 10;
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR, year);
calendar.set(Calendar.MONTH, month);
int numDays = calendar.getActualMaximum(Calendar.DATE);
SimpleDateFormat df = new SimpleDateFormat("dd/MMM/yyyy");
calendar.set(Calendar.DAY_OF_MONTH,1);
%>
<SCRIPT language="javascript">
var count=1;
var numDays = "<%=numDays %>";
while(count <= numDays-1 ) {
count++;
// calendar.set(Calendar.DAY_OF_MONTH,count); //error in this part when uncommented
$("#addRow").trigger("click");
}
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var cell1 = row.insertCell(0);
var element1 = document.createElement("input");
element1.type = "checkbox";
element1.name="chkbox[]";
cell1.appendChild(element1);
var cell2 = row.insertCell(1);
cell2.innerHTML = "<%= df.format(calendar.getTime()) %>"; //new date here
var cell3 = row.insertCell(2);
var element2 = document.createElement("input");
element2.type = "text";
element2.name = "txtbox[]";
cell3.appendChild(element2);
}
</SCRIPT>
</BODY>
Not able to use calendar.set(Calendar.DAY_OF_MONTH,count) within the loop, so that date is incremented on each click. When running calendar.set(Calendar.DAY_OF_MONTH,1); it is displaying output as given in image
snapshot of output when setting DAY_OF_MONTH outside the loop
I have found the answer. Actually its a other way workout.
Have fetched the no of days in the calendar (from server date) and run a loop for each count trigger the addrow button incrementing the label value.
JS code =>
numDays = "<%= numDays%>";
while (count <= numDays - 1) {
count = count + 1;
$("#btnAddRow").trigger("click");
}
function addRow(tableID) {
var countCol = parseInt($('#dataTable').attr('data-countCol'), 10) || 1;
countRow = countRow + 1;
var index = $("#dataTable tr:last").attr("id").split("_")[1];
var rid = "r_" + (parseInt(index) + 1);
var tempRow = $("#dataTable tr:last").clone(true, true);
tempRow.attr("id", rid);
var checkCol = $('#dataTable tr:last td:first input');
checkCol.prop("check", true);
checkCol.prop("id", "check-" + index);
var dateCol = $('#dataTable tr:last td:nth-child(2) input');
dateCol.prop("readonly", true);
var pv_dt = dateCol.val().split("/");
pv_dt[0] = parseInt(pv_dt[0]) + 1;
var nw_dt = pv_dt.join("/");
$(tempRow).find('td:nth-child(2) input').val(nw_dt);
tempRow.find('td:nth-child(3) input').prop('name', "rom_" + parseInt(countRow) + "." + countCol);
tempRow.find('td:nth-child(4) input').prop('name', "waste_" + parseInt(countRow) + "." + countCol);
tempRow.find('td:nth-child(5) input').prop('name', "fh_" + parseInt(countRow) + "." + countCol);
tempRow.find('td:nth-child(6) input').prop('name', "ot-rom_" + parseInt(countRow) + "." + countCol);
tempRow.find('td:nth-child(7) input').prop('name', "ot-waste_" + parseInt(countRow) + "." + countCol);
tempRow.find('td:nth-child(8) input').prop('name', "ot-FH_" + parseInt(countRow) + "." + countCol);
$('#dataTable').append(tempRow);
}

How re-order rows when row is hidden

I want to be re-order the based on which field has been hidden, I set the hidden field zone zone_deleted to 1 when it it has been hidden to mark it as deleted.
function insertZone() {
var table = document.getElementById('zoneItems');
var e = document.getElementById('zone');
var number = e.options[e.selectedIndex].value;
var rowcount = document.getElementById('zoneItems').rows.length;
if(rowcount == 0){
var x = table.insertRow(-1);
var head1 = x.insertCell(0);
head1.innerHTML = "Zone";
var head2 = x.insertCell(1);
head2.innerHTML = "Motor Reference Point";
var head3 = x.insertCell(2);
head3.innerHTML = " ";
}
for (var i=0; i < number; i++)
{
var x = table.insertRow(-1);
var a = x.insertCell(0);
//a.innerHTML = "<input type='hidden' name='zone_id' value='' /> ";
num = i+1;
var b = x.insertCell(1);
b.innerHTML = "<input type='text' name='zone_description[]' size='18' value=''/><input id='zone"+num+"' type='hidden' name='zone_deleted[]' value='0' />";
var c = x.insertCell(2);
c.innerHTML = "<button type='button' class='button lastChild' onclick='removeZone(this)' ><img src='themes/default/images/id-ff-clear.png'></button>";
}
//set the row ordering
count();
}
function removeZone(rows) {
var _row = rows.parentElement.parentElement;
_row.cells[1].getElementsByTagName('input')[1].value = '1';
document.getElementById('zoneItems').rows[_row.rowIndex].style.display = 'none';
count();
}
function count(){ //sets the row ordering
var table = document.getElementById("zoneItems");
var tbody = table.tBodies[0];
for (var i = 0, row; row = tbody.rows[i]; i++) { //loop through rows
if(i != 0){//if not the first row
// var deleted = row.cells[1].getElementsByTagName('input')[1].value;
for (var j = 0, col; col = row.cells[j]; j++) {//loop through cols
if(j == 0){//insert into only the first td
col.innerHTML = "<span>" +i+ "</span><input type='hidden' name='zone_id' value='' />";
}
}
}
}
}
Use a different variable for the row number that's displayed than the one used to index the rows in the DOM.
function count() {
var table = document.getElementById("zoneItems");
var tbody = table.tBodies[0];
var rownum = 1;
for (var i = 1, row; row = tbody.rows[i]; i++) { //loop through rows
var deleted = row.cells[1].getElementsByTagName('input')[1].value;
if (deleted != "1") {
row.cells[0].innerHTML = "<span>" +rownum+ "</span><input type='hidden' name='zone_id' value='' />";
rownum++;
}
}
}
FIDDLE

Categories

Resources