I want to create a html table layout in jQuery - javascript

I am trying to create an Html table layout using jQuery but I don't know where I am doing mistakes.
When I try to run this and check the console tab the error comes with undefined( i and table2)
I just want to show the table on the chrome page means I want the output.
$(document).ready(function() {
function table() {
this.column = col;
}
function col(value1, value2) {
var multiply = (value1 * value2);
return multiply;
}
var table2 = new table();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1>Table Layout</h1>
<table border="solid 3px" style="font-size: 20px;" width="100%">
<thead>
<tr>
<script>
for (var j = 1; j <= 10; j++) {
console.log("<th><label'>" + i + "</label></th>");
}
</script>
</tr>
</thead>
<tbody>
<script>
for (var i = 1; i <= 5; i++) {
console.log("<tr>");
for (var k = 1; k <= 5; k++) {
var value1 = i;
var value2 = k;
console.log("<td>" + table2.column(value1, value2) + "</td>");
}
console.log("</tr>");
}
</script>
</tbody>
</table>

This should do it.
There was an i inside but it should be an j
console.log("<th><label'>" + j + "</label></th>");
I copied your jquery code before the table2 call.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1>Table Layout</h1>
<table border="solid 3px" style="font-size: 20px;" width="100%">
<thead>
<tr>
<script>
for (var j = 1; j <= 10; j++) {
console.log("<th><label'>" + j + "</label></th>");
}
</script>
</tr>
</thead>
<tbody>
<script>
function table() {
this.column = col;
}
function col(value1, value2) {
var multiply = (value1 * value2);
return multiply;
}
var table2 = new table();
for (var i = 1; i <= 5; i++) {
console.log("<tr>");
for (var k = 1; k <= 5; k++) {
var value1 = i;
var value2 = k;
console.log("<td>" + table2.column(value1, value2) + "</td>");
}
console.log("</tr>");
}
</script>
</tbody>
</table>

There are these issues:
console.log will not write to the page (the DOM), but to the console area.
The code in the inline script elements will run before the code in the ready handler, so table will not be defined yet.
Defining a constructor with the only purpose to store a function is bad practice. If this is only to do a multiplication then even a plain function is overkill.
As you use jQuery, use it to the full, and populate the table by creating elements with jQuery instead of concatenating strings.
Style your table with CSS classes, not with a style and border attributes. The value you gave to the border attribute is invalid. It accepts values "0" or "1".
The number of cells you generated for the head-row does not correspond to the number of columns in the body of the table.
Here is corrected code:
$(document).ready(function() {
var $titles = [];
for (var j = 1; j <= 5; j++) {
$titles.push($("<th>").append($("<label>").text(j)));
}
$("thead tr").append($titles);
var $rows = [];
for (var i = 1; i <= 5; i++) {
var $row = $("<tr>");
for (var k = 1; k <= 5; k++) {
$row.append($("<td>").text(i * k));
}
$rows.push($row);
}
$("tbody").append($rows);
});
table {
border-collapse: collapse;
font-size: 20px;
width: 100%;
}
td, th {
border: solid 3px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1>Table Layout</h1>
<table>
<thead>
<tr>
</tr>
</thead>
<tbody>
</tbody>
</table>

console.log does not add anything to the DOM
You had i inside a loop with j
Your head code ran to 10, the body code to 5
I think you might mean this
function col(value1, value2) {
var multiply = (value1 * value2);
return multiply;
}
$(document).ready(function() {
const $table = $("#table1");
const $thead = $("thead", $table)
const $tbody = $("tbody", $table)
for (let i = 1; i <= 5; i++) {
$thead.append(`<th><label>${i}</label></th>`);
const $tr = $tbody.append('<tr/>')
for (let k = 1; k <= 5; k++) {
$tr.append($(`<td/>`, { text: col(i, k) }));
}
}
});
#table1 {
border-collapse: collapse;
font-size: 20px;
width: 100%
}
th,
td {
border: solid 3px;
text-align: center;
width: 20px
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1>Table Layout</h1>
<table id="table1">
<thead>
</thead>
<tbody>
</tbody>
</table>
To not update the DOM in every loop, push the html to an array
const col = (value1, value2) => value1 * value2;
const range = (start, stop, step) => Array.from({ length: (stop - start) / step + 1}, (_, i) => start + (i * step));
$(document).ready(function() {
const $table = $("#table1");
const $thead = $("thead", $table);
const $tbody = $("tbody", $table);
const arr = range(1,5,1); // from 1 to 5 step 1
$thead.html(arr.map(i => `<th><label>${i}</label></th>`).join(''));
$tbody.html(arr.map(i => `<tr/>${arr.map(k => `<td>${col(i, k)}</td>`)}</tr>`).join(''))
});
#table1 {
border-collapse: collapse;
font-size: 20px;
width: 100%
}
th,
td {
border: solid 3px;
text-align: center;
width: 20px
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1>Table Layout</h1>
<table id="table1">
<thead>
</thead>
<tbody>
</tbody>
</table>

Simpling adding console.log inside a script tag in you required place will not add the content to the DOM. You have to manipulate the template as string and set it as the html content of the target using html method in jQuery.
Also the loop index used in the for loop was j and you were consoling it with i. The index was looping till 10. But you have only 5 columns inside a row. If that is not purposeful, you have to user loop from 1 to 5
$(document).ready(function () {
maniputalteHeader();
function table() {
this.column = col;
}
function col(value1, value2) {
var multiply = (value1 * value2);
return multiply;
}
var table2 = new table();
let template = '';
for (var i = 1; i <= 5; i++) {
template += "<tr>";
for (var k = 1; k <= 5; k++) {
var value1 = i;
var value2 = k;
template += "<td>" + table2.column(value1, value2) + "</td>";
}
template += "</tr>";
}
$("#tbody").html(template);
});
function maniputalteHeader() {
let template = '';
for (var j = 1; j <= 5; j++) {
template += "<th><label'>" + j + "</label></th>";
}
$("#thead").html(template);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1>Table Layout</h1>
<table border="solid 3px" style="font-size: 20px;" width="100%">
<thead>
<tr id="thead">
</tr>
</thead>
<tbody id="tbody">
</tbody>
</table>

Related

How to overwrite data in a table?

Trying to create a table with data-attributes when clicking on a link
The problem is most likely in this code
I can not understand how to rewrite the data in the table.
Now the data is sequentially added to the table.
My code - https://jsfiddle.net/347x8bwq/
(function() {
'use strict';
function createTable() {
let link = document.querySelectorAll('.link');
let block = document.querySelector('.block');
let blockTable = document.querySelector('.table');
for (let i = 0; i < link.length; i++) {
let links = link[i];
links.addEventListener('click', function(e) {
e.preventDefault();
let linkData = this.dataset;
for (let j in linkData) {
let tableRow = document.createElement('tr');
let arr = linkData[j].split('|');
for (let k = 0; k < arr.length; k++) {
let tableCol = document.createElement('td');
tableCol.innerHTML = arr[k];
tableRow.appendChild(tableCol);
}
blockTable.appendChild(tableRow);
}
});
}
}
createTable();
Desired behavior - when clicking on a link each time - a new table was created
Before you append your tableRow to the blockTable, clear its innerHTML.
(function() {
'use strict';
function createTable() {
let link = document.querySelectorAll('.link');
let block = document.querySelector('.block');
let blockTable = document.querySelector('.table');
for (let i = 0; i < link.length; i++) {
let links = link[i];
links.addEventListener('click', function(e) {
e.preventDefault();
let linkData = this.dataset;
blockTable.innerHTML = "";
for (let j in linkData) {
let tableRow = document.createElement('tr');
let arr = linkData[j].split('|');
for (let k = 0; k < arr.length; k++) {
let tableCol = document.createElement('td');
tableCol.innerHTML = arr[k];
tableRow.appendChild(tableCol);
}
blockTable.appendChild(tableRow);
}
});
}
}
createTable();
})();
.table {
width: 100%;
table-layout: fixed;
}
td {
border: 1px solid #ccc;
}
.link {
display: block;
margin-bottom: 5px;
}
.block {
padding: 25px;
border: 1px solid #000;
}
Link 1
Link 2
Link 3
<div class="block">
<table class="table">
<tr>
<td>Атрибут1</td>
<td>Title</td>
</tr>
<tr>
<td>Атрибут2</td>
<td>Subtitle</td>
</tr>
<tr>
<td>Атрибут3</td>
<td>1234</td>
</tr>
</table>
</div>
See - https://jsfiddle.net/2wvm6de8/
You have to clear the table before adding a new elements. Just add blockTable.innerHTML = ''; after e.preventDefault();
https://jsfiddle.net/vLm60kzq/

How to delete table cells properly

I am trying to delete table rows and table column. For that i have written two functions. The DelelteRow() and DeleteColumn() delete the cells which have
index greater then zero. But actually one row or column should be deleted at a time. can some one modify my code.
DeleteRow:
function DeleteRows() {
var tbl = document.getElementById('myTable'),
lastRow = tbl.rows.length - 1,
i;
for (i = lastRow; i > 0; i--) {
tbl.deleteRow(i);
}
}
DeleteColumn:
function DeleteColumns() {
var tbl = document.getElementById('myTable'),
lastCol = tbl.rows[0].cells.length - 1,
i, j;
for (i = 0; i < tbl.rows.length; i++) {
for (j = lastCol; j > 0; j--) {
tbl.rows[i].deleteCell(j);
}
}
Something like this will delete one row/column at a time. Your question is not entirely clear which row/column you'd like removed, but your code implies you only want the last row/column removed.
var delRowBtn = document.querySelector('.delRow');
delRowBtn.addEventListener('click', deleteLastRow);
var delColBtn = document.querySelector('.delCol');
delColBtn.addEventListener('click', deleteLastColumn);
var tbl = document.querySelector('table');
function deleteLastRow() {
tbl.deleteRow(tbl.rows.length - 1);
}
function deleteLastColumn() {
var lastCol = tbl.rows[0].cells.length - 1;
for (var i = 0; i < tbl.rows.length; i++) {
tbl.rows[i].deleteCell(lastCol);
}
}
html, body {
font-size: 24px;
}
table {
margin-top: 30px;
}
td {
padding: 10px;
outline: 1px solid lightgrey;
}
<button class="delRow">Delete Row</button>
<button class="delCol">Delete Column</button>
<table>
<tbody>
<tr>
<td>r0c0</td>
<td>r0c1</td>
<td>r0c2</td>
<td>r0c3</td>
<td>r0c4</td>
</tr>
<tr>
<td>r1c0</td>
<td>r1c1</td>
<td>r1c2</td>
<td>r1c3</td>
<td>r1c4</td>
</tr>
<tr>
<td>r2c0</td>
<td>r2c1</td>
<td>r2c2</td>
<td>r2c3</td>
<td>r2c4</td>
</tr>
</tbody>
</table>

Unable to print table grid using jQuery

I am unable to print a grid. This is what I am trying to do:
Take the grid size as an input from the user.
Dynamically create the grid based on the input.
Below is a part of the code.
$(document).ready(function() {
$("#grid-input").click(function() {
$(".drawing-area").empty();
var rows = $("#row").val();
var cols = $("#col").val();
if (rows > 0 && cols > 0) {
for (var i = 1; i <= rows; i++) {
var rowClassName = 'row' + i;
$('<tr></tr>').addClass(rowClassName).appendTo('.drawing-area'); //Adding dynamic class names whenever a new table row is created
for (var j = 1; j <= cols; j++) {
var colClassName = 'col' + j;
$('<td width="20px" height="20px" style="border: 1px solid #000"></td>').addClass(colClassName).appendTo('.rowClassName');
}
}
} else {
alert("You haven't provided the grid size!");
}
});
});
});
<table class="drawing-area">
</table>
There is an error in your code, Last brackets are not required.
Append dom at the end of your code,
Try following code
$(document).ready(function() {
$("#grid-input").click(function() {
$(".drawing-area").empty();
var rows = $("#row").val();
var cols = $("#col").val();
if (rows > 0 && cols > 0) {
for (var i = 1; i <= rows; i++) {
var rowClassName = 'row' + i;
var tr = $('<tr>').addClass(rowClassName);
tr.appendTo('.drawing-area'); //Adding dynamic class names whenever a new table row is created
for (var j = 1; j <= cols; j++) {
var colClassName = 'col' + j;
$('<td width="20px" height="20px" style="border: 1px solid #000">').addClass(colClassName).appendTo(tr);
}
}
} else {
alert("You haven't provided the grid size!");
}
});
});
You can try to save the dynamic table row to a variable $tr first and then add the dynamic table column to that $tr variable like:
$("#grid-input").click(function() {
$(".drawing-area").empty();
var rows = $("#row").val();
var cols = $("#col").val();
if (rows > 0 && cols > 0) {
for (var i = 1; i <= rows; i++) {
var rowClassName = 'row' + i;
// Saving dynamic table row variable
var $tr = $('<tr/>').addClass(rowClassName).appendTo('.drawing-area');
for (var j = 1; j <= cols; j++) {
var colClassName = 'col' + j;
$('<td>'+ (i * j) +'</td>').addClass(colClassName)
// Append the new td to this $tr
.appendTo($tr);
}
}
} else {
alert("You haven't provided the grid size!");
}
});
.drawing-area{font-family:"Trebuchet MS",Arial,Helvetica,sans-serif;border-collapse:collapse;width:100%}
.drawing-area td,.drawing-area th{border:1px solid #ddd;padding:8px}
.drawing-area tr:nth-child(even){background-color:#f2f2f2}
.drawing-area tr:hover{background-color:#ddd}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Row: <input type="number" id="row"><br/>
Col: <input type="number" id="col"><br/>
<button id="grid-input">Save</button><br/><br/>
<table class="drawing-area">
</table>

find the <td> column value of respective cell using any javascript library

<table border="1">
<tr>
<td rowspan="3">0</td>
<td>1</td>
<td rowspan="3">2</td>
<td>3</td>
</tr>
<tr>
<td>A</td>
<td>B</td>
</tr>
<tr>
<td>X</td>
<td>Y</td>
</tr>
</table>
I want to find the column number of td containing X using jQuery or some other JavaScript library.
For example column number of td containing A is 1 and B is 3.
Also we know that column number of td containing X is 1. But how can we get that pragmatically.
My case here is I need to merge data of all the rows with first row. So while moving through each td I need to know from which column does it belong so that I can merge it to the td of first row of that column.
Please help me if there is any other approach to solve my problem.
Here is the Fiddle.
It gets the index and looks for rowspans and calculates the visible index.
function getColumnNumber(text) {
var $table = $("table").eq(0);
$("td:contains(" + text + ")").css("color", "red");
var $td = $("td:contains(" + text + ")"),
$tr = $td.parent(),
tdPosition = $td.index(),
trPosition = $tr.index(),
position = parseInt(tdPosition);
for (i = 0; i < trPosition; i++) {
for (j = 0; j <= tdPosition; j++) {
var rowSpan = parseInt($table.find('tr').eq(i).find('td').eq(j).attr("rowspan"));
if (typeof rowSpan !== "number") {
rowSpan = 0;
}
if (rowSpan > trPosition) {
position++;
tdPosition++;
}
}
}
console.log(text + " pos: " + position);
return position;
};
getColumnNumber('A');
getColumnNumber('B');
getColumnNumber('1');
getColumnNumber('Y');
This approach is basically storing your table data into an array, and intended if you ever want to expand or modify the structure of your table rowspan. (This does not support colspan)
$(function() {
var tableArr = [],
totalRow = $('table tr').length,
totalCol = 0;
$('table tr').each(function() {
var colLength = $(this).children('td').length;
totalCol = colLength > totalCol ? colLength : totalCol;
});
for (var r = 0; r < totalRow; r++) {
var row = [];
for (var c = 0; c < totalCol; c++) {
row.push(null);
}
tableArr.push(row);
}
$('td').each(function() {
var rowspan = $(this).attr('rowspan');
var rowIndex = $(this).parent('tr').index();
var colIndex = $(this).index();
var text = $(this).html();
if (rowspan && rowspan > 0) {
for (var i = 0; i < rowspan; i++) {
tableArr[i][colIndex] = text;
}
} else {
var lastNull = tableArr[rowIndex].indexOf(null);
tableArr[rowIndex][lastNull] = text;
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table border="1">
<tr>
<td rowspan="3">0</td>
<td>1</td>
<td rowspan="3">2</td>
<td>3</td>
</tr>
<tr>
<td>A</td>
<td>B</td>
</tr>
<tr>
<td>X</td>
<td>Y</td>
</tr>
</table>
Your table information is stored within tableArr, which you use to query if you want to get desired columnIndex based on the content of your td.
Usage
// This returns an array containing [row, column];
function getPositionByText(str) {
for (var r = 0; r < tableArr.length; r++) {
for (var c = 0; c < tableArr[r].length; c++) {
if (tableArr[r][c] === str) {
return [r, c]
}
}
}
return null;
}
var position = getPositionByText('X');
var xRow = position[0];
var xCol = position[1];

FInd a control s value inside a table in tr

I have this table and I want to find a hidden control's value inside the tr .
I tried this javascript
function DeleteGridview_Row(pid) {
alert(pid);
var table = document.getElementById('<%= gvResults_gov.ClientID %>');
rows = table.getElementsByTagName('tr');
var i;
var j;
var cells;
var customerId;
for (i = 0, j = rows.length; i < j; ++i) {
cells = rows[i].getElementsByTagName('td');
if (!cells.length) {
continue; }
customerId = cells[0].innerHTML;
}
alert(customerId);
}
HTML
<table cellpadding="4" style="color: #333333; border-width: 0px; border-style: Groove;
width: 100%; font-weight: bold; width: 100%;" id="MainContent_gvResults_gov"
class="box-table-b">
<tbody>
<tr >
<td>
<input type="hidden" value="6532" id="MainContent_gvResults_gov_hdDocID_0" name="ctl00$MainContent$gvResults_gov$ctl02$hdTocID">
</td>
<td>
1010041215
</td>
</tr>
</tbody>
</table>
remove the enter code here
if the code is complete you need an ending }
If the customer ID is 1010041215 you need the second cell (from 0)
for (i = 0, j = rows.length; i < j; ++i) {
cells = rows[i].getElementsByTagName('td');
if (!cells.length) {
continue; }
customerId = cells[1].innerHTML; // [1] is the second cell
}
}
change
customerId = cells[1].innerHTML; // [1] is the second cell
to
customerId = cells[1].getElementsByTagName("input")[0].value
if you want the value of the input field
However tables have rows and cells:
function DeleteGridview_Row(pid) {
var customerId = "";
var table = document.getElementById('<%= gvResults_gov.ClientID %>');
var rows = table.rows;
for (i = 0, n = rows.length; i < n; ++i) {
cells = rows[i].cells;
if (!cells.length) {
continue; }
customerId = cells[1].innerHTML;
}
}
return customerId;
}

Categories

Resources