How to change child classes by changing only the parent class? - javascript

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

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 get text file content from web and tabulate it

I need to get a text file from server and display its contents in a table.Tried this code couldnt figure out whats wrong...........................................................................................................................................................................................................
<!DOCTYPE html>
<html>
<meta charset="UTF-8">
<head>
<style type="text/css">
body
{
font-family: Arial;
font-size: 10pt;
}
table
{
border: 1px solid #ccc;
margin: auto;
empty-cells: hide;
}
table th
{
background-color: AQUA;
color: #333;
font-weight: bold;
}
table th, table td
{
padding: 5px;
border: 1px solid #ccc;
border-color: #ccc;
}
tr:hover {background-color: #f5f5f5;}
</style>
</head>
<body>
<div align = center>
<input type="text" id="filter" placeholder="Search" title="Type a name" >
</div>
<div id="demo" align = center>
</div>
<script>
window.onload = function() {
var demo = document.getElementById("demo");
if(window.XMLHttpRequest){
var xhttp = new XMLHttpRequest();
}
else{
var xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
//xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200 || this.status == 0) {
var responseText= xhttp.responseText;
console.log(this.responseText);
document.getElementById("filter").onkeyup = filterRows;
var ROW_DELIMITER = "\n",
CELL_DELIMITER = " ";
var tableObj = {
headers: ["Time", "Duration", "Client address", "Result codes", "Bytes", "request method", "URL", "user",
"Hierarchy code", "Type"],
rows: []
};
}
function convert(responseText) {
tableObj.rows = convertToArray(responseText)
buildTable(tableObj.headers, tableObj.rows);
};
function convertToArray(text) {
return text.split(ROW_DELIMITER).map(function(row) {
return row.split(CELL_DELIMITER);
});
}
function filterRows() {
var input = this;
var rows = tableObj.rows.filter(function(row) {
var matches = row.filter(function(cell) {
return cell.toUpperCase().indexOf(input.value.toUpperCase()) > -1;
});
return matches.length > 0;
});
buildTable(tableObj.headers, rows);
}
function sortRows() {
var th = this;
var index = th.dataset.index;
tableObj.rows.sort(function(rowA, rowB) {
var textA = rowA[index].toUpperCase(),
textB = rowB[index].toUpperCase();
if (textA < textB) {
return -1;
}
if (textA > textB) {
return 1;
}
return 0;
});
buildTable(tableObj.headers, tableObj.rows);
}
function buildTable(headers, rows) {
var table = document.createElement('table');
var tr = document.createElement('tr');
table.appendChild(tr);
for (var i = 0; i < headers.length; i++) {
th = document.createElement('th');
tr.appendChild(th);
th.innerHTML = headers[i];
th.onclick = sortRows;
th.dataset.index = i;
}
for (var j = 0; j < rows.length; j++) {
tr = document.createElement('tr');
table.appendChild(tr);
for (var k = 0; k < rows[j].length; k++) {
var td = document.createElement('td');
tr.appendChild(td);
td.innerHTML = rows[j][k];
td.dataset.index = k;
}
}
demo.innerHTML = '';
demo.appendChild(table);
}
convert(responseText);
xhttp.open("GET", "https://www.w3.org/TR/PNG/iso_8859-1.txt", true);
xhttp.send(null);
};
</script>
</body>
</html>

i want to create table dynamically in a specific position of the html page

i am trying to create the table using js in a specific location of the page
i m getting the output but also getting an error undefind before the result
before the table creation an error is shown undefine any solution for this
<script>
function tab()
{
var x=4;
function tabb(){
var table = document.createElement('table');
table.id="a-table";
for (var i = 1; i < x; i++){
var tr = document.createElement('tr');
tr.id="myrow";
var td1 = document.createElement('td');
var td2 = document.createElement('td');
tr.appendChild(td1);
tr.appendChild(td2);
table.appendChild(tr);
}
document.body.appendChild(table);
}
document.getElementById("tab").innerHTML=tabb();
var cells = document.getElementById("a-table").getElementsByTagName("td");
var i=0;
for(i = 0; i < x+1; i++){
var cell = cells[i];
cell.innerHTML = "<img class=img1 src=faculty/comm/"+i+".jpg>";
}
}
</script>
<style>
td {
border: solid 1px #000;
border-style: none solid solid none;
padding: 10px;
border-radius:8px;
}
</style>
<body>
<input type=button onclick="tab()" value="create">
<div id="tab"></div>
</body>
Even though this will remove the undefined from the page, I strongly recommend you to consider more clean, optimized tab function.
function tab()
{
var x=4;
var table = document.createElement('table');
table.id="a-table";
for (var i = 0; i < x; i++){
var tr = document.createElement('tr');
tr.id="myrow";
var td1 = document.createElement('td');
var td2 = document.createElement('td');
tr.appendChild(td1);
tr.appendChild(td2);
table.appendChild(tr);
}
document.getElementById("tab").appendChild(table);
var cells = document.getElementById("a-table").getElementsByTagName("td");
var i=0;
for(i = 0; i < x+1; i++){
var cell = cells[i];
cell.innerHTML = "<img class=img1 src=faculty/comm/"+i+".jpg>";
}
}
td {
border: solid 1px #000;
border-style: none solid solid none;
padding: 10px;
border-radius:8px;
}
<input type=button onclick="tab()" value="create">
<div id="tab"></div>

improve csv file reader by removing quotes from fields, supporting a header, and allowing other seperators

I would like my file to not have quotations when displayed in html. Meaning there are quotes by every word. I would like to take that away.
And I would also like to add a th tag so I can have a header.
And I don't wanna just have comma separated, I also wanna have other separators such as |
Here is my code:
css:
table
{
border: 1px solid #ccc;
}
table th
{
background-color: #F7F7F7;
color: #333;
font-weight: bold;
}
table th, table td
{
padding: 5px;
border-color: #ccc;
}
Javascript:
$(function () {
$("#upload").bind("click", function () {
var regex = /^([a-zA-Z0-9\s_\\.\-:])+(.csv|.txt)$/;
if (regex.test($("#fileUpload").val().toLowerCase())) {
if (typeof (FileReader) != "undefined") {
var reader = new FileReader();
reader.onload = function (e) {
var table = $("<table />");
var rows = e.target.result.split("\n");
for (var i = 0; i < rows.length; i++) {
var row = $("<tr />");
var cells = rows[i].split(",");
for (var j = 0; j < cells.length; j++) {
var cell = $("<td />");
cell.html(cells[j]);
row.append(cell);
}
table.append(row);
}
$("#dvCSV").html('');
$("#dvCSV").append(table);
}
reader.readAsText($("#fileUpload")[0].files[0]);
} else {
alert("This browser does not support HTML5.");
}
} else {
alert("Please upload a valid CSV file.");
}
});
});
HTML:
<input type="file" id="fileUpload" />
<input type="button" id="upload" value="Upload" />
<hr />
<div id="dvCSV">
</div>
So I took a look at your code and made a jsfiddle off of it.
Heres the full fiddle
$(function() {
$("#upload").bind("click", function() {
var regex = /^([a-zA-Z0-9\s_\\.\-:])+(.csv|.txt)$/;
if (regex.test($("#fileUpload").val().toLowerCase())) {
if (typeof(FileReader) != "undefined") {
var reader = new FileReader(),
table = $("<table>"),
separator = ',',
rows,
rowLength;
reader.onload = function(e) {
rows = e.target.result.split(/[\r\n|\n]+/);
rowLength = rows.length;
for (var i = 0; i < rowLength; i++) {
var row = $("<tr>"),
cells = rows[i].split(separator),
cellLength = cells.length,
cell;
for (var j = 0; j < cellLength; j++) {
// Special case for the first row
cell = (i === 0) ? $("<th>") : $("<td>");
cell.html(cells[j]);
row.append(cell);
}
// Special case for first row (thead)
if (i === 0) {
row = $('<thead>').html(row);
}
table.append(row);
}
$("#dvCSV").html('');
$("#dvCSV").append(table);
}
reader.readAsText($("#fileUpload")[0].files[0]);
} else {
alert("This browser does not support HTML5.");
}
} else {
alert("Please upload a valid CSV file.");
}
});
});
a {
display: block;
}
table {
border: 1px solid #ccc;
}
table th {
background-color: #F7F7F7;
color: #333;
font-weight: bold;
}
table th,
table td {
padding: 5px;
border-color: #ccc;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
Dummy CSV
<input type="file" id="fileUpload" />
<input type="button" id="upload" value="Upload" />
<hr />
<div id="dvCSV">
</div>
I made slight adaptations to it. It turns out (at least from the dummy csv I am using), that no quotes are being added...
The split-by-rows regex was not seeming to work, so I changed it to:
var rows = e.target.result.split(/[\r\n|\n]+/);
In the comments you wanted to add thead and th support. To do that, I just added a conditional on the two lines:
cell = (i === 0) ? $("<th>") : $("<td>");
if (i === 0) {
row = $('<thead>').html(row);
}
You mentioned wanting to separate on things other than a comma. As you already know, you are dealing with "Comma-Separated-Values", so separating by comma is expected... but to make your code more generic, I added the separator in a variable instead (so you can swap that out with what you expect the separator to be):
var separator = ',';
var cells = rows[i].split(separator);
Hope that helped! :)
$(function() {
$("#upload").bind("click", function() {
var regex = /^([a-zA-Z0-9\s_\\.\-:])+(.csv|.txt)$/;
if (regex.test($("#fileUpload").val().toLowerCase())) {
if (typeof(FileReader) != "undefined") {
var reader = new FileReader(),
table = $("<table>"),
separator = ',',
rows,
rowLength;
reader.onload = function(e) {
rows = e.target.result.split(/[\r\n|\n]+/);
rowLength = rows.length;
for (var i = 0; i < rowLength; i++) {
var row = $("<tr>"),
cells = rows[i].split(separator),
cellLength = cells.length,
cell;
for (var j = 0; j < cellLength; j++) {
// Special case for the first row
cell = (i === 0) ? $("<th>") : $("<td>");
cell.html(cells[j]);
row.append(cell);
}
// Special case for first row (thead)
if (i === 0) {
row = $('<thead>').html(row);
}
table.append(row);
}
$("#dvCSV").html('');
$("#dvCSV").append(table);
}
reader.readAsText($("#fileUpload")[0].files[0]);
} else {
alert("This browser does not support HTML5.");
}
} else {
alert("Please upload a valid CSV file.");
}
});
});
a {
display: block;
}
table {
border: 1px solid #ccc;
}
table th {
background-color: #F7F7F7;
color: #333;
font-weight: bold;
}
table th,
table td {
padding: 5px;
border-color: #ccc;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
Dummy CSV
<input type="file" id="fileUpload" />
<input type="button" id="upload" value="Upload" />
<hr />
<div id="dvCSV">
</div>

How to create a two-dimensional array within a table?

I would like to create a table for a Connect Four game, I would like to do this by setting a two-dimensional 7*6 array and put each array within each cell if that makes sense. I am new to Javascript and do not have lot of knowledge in object orientated programming. I am trying to give each cell a xPosition and yPosition (coordinates, perhaps this could be in their "id") so that the game can check if there is a row or column of Blue or yellow.
Code so far, rough attempt:
function make()
{
var table = document.createElement("table");
for (var i = 0; i < 6; i++)
{
var row = table.inserRow();
for (var j = 0; j < 5; j++)
{
var cell = row.insertCell;
}
document.body.appendChild(table);
}
}
Some really quick solution written with jQuery. I pasted whole html, so you can save it out as html file and open in a browser. You can click on cells to see coordinates (0-based).
<html>
<head>
<title>GRID</title>
<style type="text/css">
table tr td { width: 50px; height: 50px; background-color: silver; border: 1px solid black; }
table tr td.over { background-color: yellow; }
table tr td.active { background-color: red; }
.controls { padding: 20px; }
</style>
</head>
<body>
<div class="controls">
left
top
right
bottom
topleft
topright
bottomright
bottomleft
</div>
<table></table>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var rows = 6,
cols = 7;
for(var i = 0; i < rows; i++) {
$('table').append('<tr></tr>');
for(var j = 0; j < cols; j++) {
$('table').find('tr').eq(i).append('<td></td>');
$('table').find('tr').eq(i).find('td').eq(j).attr('data-row', i).attr('data-col', j);
}
}
$('table tr td').mouseover(function() {
$(this).addClass('over');
}).mouseout(function() {
$(this).removeClass('over');
}).click(function() {
$(this).addClass('active');
});
$(".controls a").click(function() {
var $active = $("table tr td.active");
if($active.length > 0) {
var move = $.parseJSON($(this).attr('data-move'));
if(move.length >= 2) {
$active.each(function() {
var row = parseInt($(this).attr('data-row')) + move[1],
col = parseInt($(this).attr('data-col')) + move[0];
if(col >= cols) col = cols - 1;
if(col < 0) col = 0;
if(row >= rows) row = rows - 1;
if(row < 0) row = 0;
$(this).removeClass('active');
$('table tr').eq(row).find('td').eq(col).addClass('active');
});
}
}
});
});
</script>
</body>
</html>
Notice that if you change rows and cols variables you can draw bigger grids.
I have added controls div with buttons so you can play with directions. First of all you need to mark element as active, and them you can click to move.
There is one bug (or feature in my opinion) that you can mark multiple fields and move them all at once.
It's good base to start with!

Categories

Resources