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/
Related
I'm creating a homework calculator. I need to recursively create form elements, and found out how to make a recursively creating table. How do I turn the spaces in that table into form elements that create themselves recursively? If this isn't clear, please tell me.
<table id="xTable"></table>
<script>
var rQty = parseInt(prompt("Number of Rows"), 10);
var cQty = parseInt(prompt("Number of Columns"), 10);
var table = document.getElementById("xTable");
for (let i = 0; i < rQty; i++) {
var row = table.insertRow();
for (let j = 0; j < cQty; j++) {
var cell = row.insertCell();
cell.textContent = "I want to make this into a recursive form creator ";
}
}
</script>
<style>
td {
border: 2px ridge #333;
text-align: center;
}
</style>
It's rather simple, just create the elements you want to insert into the cells with document.createElement, then set the properties you want them to have and use cell.appendChild to place them into the cell.
This example creates <input type="text"> elements:
var rQty = parseInt(prompt("Number of Rows"), 10);
var cQty = parseInt(prompt("Number of Columns"), 10);
var table = document.getElementById("xTable");
for (let i = 0; i < rQty; i++) {
var row = table.insertRow();
for (let j = 0; j < cQty; j++) {
var cell = row.insertCell();
var input = document.createElement('input');
input.type = 'text';
input.name = 'input_r' + i + '-c' + j;
cell.appendChild(input);
}
}
td {
border: 2px ridge #333;
text-align: center;
}
<table id="xTable"></table>
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>
i want to find the minimum value of each row also minimum value of each column
add input to each row and column produced after the table generation
want to find minimum value of each row and minimum value of each column
also minimum value of whole table
i want to input the user values instead of default value cell in fiddle given below
[fiddle][1]
(function (window, document, undefined) {
"use strict";
var wrap = document.getElementById("wrap"),
setColumn = document.getElementById("column"),
setRow = document.getElementById("row"),
btnGen = document.getElementById("btnGen"),
btnCopy = document.getElementById("btnCopy");
btnGen.addEventListener("click", generateTable);
btnCopy.addEventListener("click", copyTo);
function generateTable(e) {
var newTable = document.createElement("table"),
tBody = newTable.createTBody(),
nOfColumns = parseInt(setColumn.value, 10),
nOfRows = parseInt(setRow.value, 10),
row;
newTable.createCaption().appendChild(document.createTextNode("Generated Table"));
for (var i = 0; i < nOfRows; i++) {
row = generateRow(nOfColumns);
tBody.appendChild(row.cloneNode(true));
}
(wrap.hasChildNodes() ? wrap.replaceChild : wrap.appendChild).call(wrap, newTable, wrap.children[0]);
}
function generateRow(n) {
var row = document.createElement("tr"),
text;
for (var i = 0; i < n; i++) {
text = document.createTextNode(Math.trunc(100 * Math.random()));
row.insertCell().appendChild(text.cloneNode(true));
}
return row.cloneNode(true);
}
function copyTo(e) {
prompt("Copy to clipboard: Ctrl+C, Enter", wrap.innerHTML);
}
}(window, window.document));
ul {
margin-left: 0;
padding-left: 0;
width: 200px;
}
ul li {
list-style: none;
padding-bottom: 1em;
}
input[type=number] {
width: 70px;
float: right;
}
table, td {
border: 1px solid #000;
padding: 5px;
border-spacing: 0;
border-collapse: collapse;
caption-side: bottom;
}
<ul>
<li>
<label for="column">Add a Column</label>
<input type="number" id="column" validate />
</li>
<li>
<label for="row">Add a Row</label>
<input type="number" id="row" />
</li>
<li>
<input type="button" value="Generate" id="btnGen" />
<input type="button" value="Copy to Clipboard" id="btnCopy" />
</li>
</ul>
<div id="wrap"></div>
please give me suggestion about it
also i want to store the minimum value of each row and column.
Check this
const generate = document.getElementById('generate');
function handleTable(cont) {
const table = cont.getElementsByTagName('table')[0],
cells = table.getElementsByClassName('cell'),
all_cells = table.getElementsByTagName('td'),
size = cells.length;
let currentValue, minimum;
const p = document.createElement('p'),
text = document.createTextNode('Minimum is: '),
minValue = document.createElement('span');
p.appendChild(text);
p.appendChild(minValue);
cont.appendChild(p);
const rowsNum = table.getElementsByTagName('tr').length,
colsNum = table.getElementsByTagName('td').length/(rowsNum);
const addInput = function(e){
currentValue = e.target.innerHTML;
e.target.innerHTML = '';
let myInput = document.createElement('input');
myInput.classList.add('my_input');
e.target.appendChild(myInput).focus();
}
const getMinimum = function(){
let cur_rows = [],
temp2 = rowsNum-1;
while(temp2--)
cur_rows.push([]);
let cur_cols = [],
temp1 = colsNum-1;
while(temp1--)
cur_cols.push([]);
let values = [];
for (let i = 0; i < size; i++){
let item = cells[i].innerHTML;
if(item){
values.push(item);
let cur_x = i % (colsNum-1),
cur_y = (i - cur_x) / (colsNum-1);
cur_cols[cur_x].push(item);
cur_rows[cur_y].push(item);
}
}
let cur_min = Math.min.apply(null, values);
minValue.innerHTML = ((cur_min && (cur_min != Infinity)) || (cur_min == 0)) ? cur_min : '';
let cur_min_rows = [];
for (let i = 0; i<cur_rows.length; i++)
cur_min_rows[i] = Math.min.apply(null, cur_rows[i]);
let cur_min_cols = [];
for (let i = 0; i < cur_cols.length; i++)
cur_min_cols[i] = Math.min.apply(null, cur_cols[i]);
for (let i = 0; i < all_cells.length; i++)
if (all_cells[i].classList.contains('result')){
let cur_x = i % colsNum,
cur_y = (i - cur_x)/(colsNum);
all_cells[i].innerHTML = '';
if ((cur_x == colsNum-1) && (cur_min_rows[cur_y] != Infinity))
all_cells[i].innerHTML = cur_min_rows[cur_y];
if ((cur_y == rowsNum-1) && (cur_min_cols[cur_x] != Infinity))
all_cells[i].innerHTML = cur_min_cols[cur_x];
}
}
const removeInput = function(e){
let elem = e.target;
if (!elem.classList.contains('my_input')) {
for (let i = size; i--;){
let input = cells[i].getElementsByClassName('my_input')[0];
if(input) {
let value = input.value;
cells[i].removeChild(input);
if(value){
value = value.replace(/ /g,'');
cells[i].innerHTML = value;
getMinimum();
}
else {
cells[i].innerHTML = currentValue;
currentValue = '';
}
}
}
}
}
for (let i = size; i--;)
cells[i].addEventListener('click', addInput);
document.body.addEventListener('click', removeInput, true);
};
const generateRow = function(cols, isLast){
let row = document.createElement('tr');
const className = (isLast) ? 'result' : 'cell';
for (let i = cols; i--;) {
let cell = document.createElement('td');
cell.classList.add(className);
row.appendChild(cell);
}
let cell = document.createElement('td');
cell.classList.add('result');
row.appendChild(cell);
if(isLast)
cell.classList.remove('result');
return row;
}
const generateTable = function(e){
const wrap = document.getElementById('wrap'),
rows = document.getElementById('rows'),
columns = document.getElementById('columns'),
newTable = document.createElement('table');
let row;
for (let i = 0; i <= rows.value; i++ ){
if(i == rows.value)
row = generateRow(columns.value, true);
else
row = generateRow(columns.value, false);
newTable.appendChild(row);
}
if (wrap.hasChildNodes())
wrap.innerHTML = '';
wrap.appendChild(newTable);
handleTable(wrap);
};
generate.addEventListener('click', generateTable);
.result, .cell{
width:30px;
height: 30px;
text-align:center;
}
.cell {
border:1px solid;
}
table {
border-collapse: collapse;
}
.my_input {
width: 25px;
text-align:center;
border:none;
outline:none;
}
ul {
width: 200px;
}
ul li {
list-style: none;
margin-bottom: 12px;
}
input[type=number] {
width: 70px;
float: right;
}
<form>
<ul>
<li>
<label>Rows</label>
<input type="number" id="rows" value="">
</li>
<li>
<label>Columns</label>
<input type="number" id="columns" value="">
</li>
<li>
<input type="button" value="Generate" id="generate">
</li>
</ul>
</form>
<div id="wrap"></div>
I have a table with black and white cells and I want to create a button which changes the colors of cells.
I have done it by using for loop jsfiddle.net
Now, I dont want to use the function below. Is it possible to change only the class atribute of whole table to change class of all td tag's?
function changeClors() {
var cells = document.getElementsByTagName('td');
for (var i = 0; i < cells.length; i++) {
cSwap(cells[i])
}
Yes it's possible you just need a css class for the table to do it and a function to toggle this class with your table.
This is how should be your css defined:
.myTable td{
background: gray;
}
And this is the JS function to toggle it in the table:
function toggleClass(){
var table = document.querySelector("table");
if(table.className !== "myTable"){
table.className = "myTable";
}else{
table.className = '';
}
}
Demo:
This is an updated Demo:
function cSwap(cell) {
if (cell.className == "t")
cell.className = "t2";
else if (cell.className == "t2")
cell.className = "t";
}
function tableCreate(n) {
var body = document.getElementsByTagName('body')[0];
var tbl = document.createElement('table');
tbl.setAttribute('onclick', 'cSwap(event.target)');
for (var i = 0; i < n; i++) {
var tr = document.createElement('tr');
for (var j = 0; j < n; j++) {
var td = document.createElement('td');
tr.appendChild(td)
td.classList.add('t');
}
tbl.appendChild(tr);
}
body.appendChild(tbl);
}
function changeClors() {
var cells = document.getElementsByTagName('td');
for (var i = 0; i < cells.length; i++) {
cSwap(cells[i])
}
}
tableCreate(5);
function toggleClass() {
var table = document.querySelector("table");
if (table.className !== "myTable") {
table.className = "myTable";
} else {
table.className = '';
}
}
td {
border: 1px solid black;
border-collapse: collapse;
padding: 28px;
}
.t {
background: white
}
.t2 {
background: black
}
.myTable td {
background: gray;
}
<body>
<input type="button" value="Change colors" onclick="changeClors()">
<input type="button" value="Change table" onclick="toggleClass()">
</body>
Instead of using the for loop, try toggling the invert class name on the table element. Then adjust the css accordingly, as in the snippet below:
function cSwap(cell) {
if (cell.className == "t")
cell.className = "t2";
else if (cell.className == "t2")
cell.className = "t";
}
function tableCreate(n) {
var body = document.getElementsByTagName('body')[0];
var tbl = document.createElement('table');
tbl.setAttribute('onclick', 'cSwap(event.target)');
tbl.setAttribute('id', 'myTable');
for (var i = 0; i < n; i++) {
var tr = document.createElement('tr');
for (var j = 0; j < n; j++) {
var td = document.createElement('td');
tr.appendChild(td)
td.classList.add('t');
}
tbl.appendChild(tr);
}
body.appendChild(tbl);
}
function changeClors() {
var table = document.getElementById('myTable');
table.classList.toggle('invert')
}
tableCreate(5);
td {
border: 1px solid black;
border-collapse: collapse;
padding: 28px;
}
.t {
background: white
}
.t2 {
background: black
}
.invert .t {
background: black
}
.invert .t2 {
background: white
}
<body>
<input type="button" value="Change colors" onclick="changeClors()">
</body>
If you're looking to just change the colors of the cells, you could toggle the class of the table and then use CSS selectors on the cells like the following:
.table-dark td { background-color: #000; }
.table-light td { background-color: #fff; }
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;
}