Clickable table - javascript

I created a simple function in JS that generates a table. Now I want to do this: when I click on some cell of the table, the page will alert the value what is inside the cell: variable b, as you can see in the code. I tried it, but I didnĀ“t managed it. is inside the code. I also used Jquery.
The code: JS
function gen() {
var rowData = '';
for (var a = 0; a < 5; a++) {
rowData += '<tr>';
for (var i = 0; i < 3; i++) {
rowData += '<td>';
rowData += b;
rowData += '</td>';
b++;
}
rowData += "</tr>";
}
$('#myTableId2').append(rowData);
}
HTML:
<table id="myTableId2"> </table>
<button onclick="gen()">Generate</button>

rowData += '<td onclick="alert(this.innerHTML)">';

I see you're using jQuery. You can attach a click() event to each <td> element as I do below.
Note that since b is undefined in your example, I took the liberty of giving it a random value for illustrative purposes.
function gen() {
let b = Math.floor(Math.random() * 1000) + 1; //generate random value
var rowData = '';
for (var a = 0; a < 5; a++) {
rowData += '<tr>';
for (var i = 0; i < 3; i++) {
rowData += '<td>';
rowData += b;
rowData += '</td>';
b++;
}
rowData += "</tr>";
}
$('#myTableId2').append(rowData);
//attach the click event using jQuery
$("td").click(function(){alert(this.innerText)});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="myTableId2"> </table>
<button onclick="gen()">Generate</button>

Related

javascript function not working (TableFilter library)

I'm trying to make a table in my web app filterable. The TableFilter library seems to be really good but I'm not able to make it work (only in the web app since it works with a simple html page).
this is the code of my page:
<html>
<head>
<title>Show Elements In Table Page</title>
<script src="~/tableFilter/tablefilter.js"></script>
<script src="~/tableFilter/tablefilter_all.js"></script>
<script src="~/tableFilter/tablefilter_all_min.js"></script>
<script src="~/tableFilter/tablefilter_min.js"></script>
</head>
<body id="pageBody" onload="createTable(getLocalItem('selectedTable'), 'elementsTable');
hideElement('loading');
document.getElementById('tableName').innerHTML = getLocalItem('selectedTable');
prova();">
<h3 id="loading">loading...</h3>
<div style="margin-left: 1em; margin-top: 1em;">
<h3 id="tableName"></h3>
<table align="left" border="1" cellpadding="5" cellspacing="0" id="elementsTable">
<!--the table loads with the createTable() function-->
</table>
</div>
<script language="javascript" type="text/javascript">
setFilterGrid("elementsTable");
<!--this is not working-->
</script>
</body>
</html>
this is the createTable() js function:
function createTable(tableName, tableId) {
fetch(domain + urlParameters + tableName)
.then(r => r.text())
.then(j => JSON.parse(j))
.then(o => {
var cols = getVarNames(o);
//header
var tableHtml = "<thead><tr>";
for (var i = 0; i < cols.length; i++) {
tableHtml += "<th>" + cols[i] + "</th>";
}
tableHtml += "</tr></thead>";
//body
tableHtml += "<tbody><tr>";
for (var i = 0; i < o.length; i++) {
for (var j = 0; j < cols.length; j++) {
tableHtml += "<td>" + o[i][cols[j]] + "</td>";
}
tableHtml += "</tr>";
}
tableHtml += "</tbody>";
//insertion in document
document.getElementById(tableId).innerHTML = tableHtml;
});
}
function getVarNames(list) {
var columns = [];
for (var i = 0; i < list.length; i++) {
var row = list[i];
for (var k in row) {
if ($.inArray(k, columns) == -1) {
columns.push(k);
}
}
}
return columns;
}
the table is loaded but it is not filterable. the script in the body seems to not recognize the table. how could i solve?
i solved creating my own query methods in javascript. maybe this could be helpful for someone.
var tableObject; //variable storing the json object form the api
function createTable(tableName, tableId) {
fetch(domain + urlParameters + tableName)
.then(r => r.text())
.then(j => JSON.parse(j))
.then(o => {
tableObject = o;
//insert filtering variables
var cols = getVarNames(tableObject);
//header
var tableHtml = "<thead><tr>";
for (var i = 0; i < cols.length; i++) {
tableHtml += "<th>" + cols[i] + "</th>";
}
//insert selection and filtering tools
tableHtml += "<tr>";
for (var i = 0; i < cols.length; i++) {
tableHtml += "<td><textarea class=\"filter\" rows=\"1\" placeholder=\"input\" style=\"resize: none;\"></textarea></td>";
//add some kind of tag matching the column -> maybe a class? or an id?
}
tableHtml += "</tr>";
tableHtml += "</tr></thead>";
//body
tableHtml += "<tbody id=\"tableBody\"><tr>";
for (var i = 0; i < tableObject.length; i++) {
if (objectIncludesFilters(tableObject[i], cols, getValuesFilters())) {
for (var j = 0; j < cols.length; j++) {
tableHtml += "<td>" + tableObject[i][cols[j]] + "</td>";
}
tableHtml += "</tr>";
}
}
tableHtml += "</tbody>";
//insertion in document
document.getElementById(tableId).innerHTML = tableHtml;
});
}
function getVarNames(list) {
var columns = [];
for (var i = 0; i < list.length; i++) {
var row = list[i];
for (var k in row) {
if ($.inArray(k, columns) == -1) {
columns.push(k);
}
}
}
return columns;
}
function getValuesFilters() {
const collection = document.getElementsByClassName("filter");
var values = [];
for (var i = 0; i < collection.length; i++) {
var value = collection[i].value;
values.push(value);
if (value == null) {
values.push("");
}
}
return values;
}
function objectIncludesFilters(obj, cols, filters) {
var result = true;
for (var i = 0; i < filters.length; i++) {
if (!obj[cols[i]].toLowerCase().includes(filters[i].toLowerCase())) {
result = false;
}
}
return result;
}

Grabbing elementID

I am creating a table with td ids as follows(id=concatenate(row,column)):
function createTable() {
document.body.innerHTML += '<table border="1" id="mytable"></table>';
for (var i = 0; i < 4; i++) {
document.getElementById("mytable").innerHTML += '<table border="1"><tr id="row' + i + '"></tr></table>';
for (var k = 0; k < 4; k++) {
document.getElementById("row" + i).innerHTML += '<td id=' + i + k + '></td>';
}
}
}
Then I want to change the background color of each cell depending on whether its value is >5 or below. This is the onclick function I call for each cell:
function clickable() {
var table = document.getElementById("mytable");
if (table != null) {
for (var i = 0; i < table.rows.length; i++) {
for (var j = 0; j < table.rows[i].cells.length; j++)
table.rows[i].cells[j].onclick = function () { colorChange(i, j); };
}
}
}
function colorChange(i, j) {
if (document.getElementById("" + i + j).innerHTML > 5) {
document.getElementById("" + i + j).style.backgroundColor = "green";
}
}
but the debugger catches a typeError for trying to access a property of null in the first line of colorChange, which means my method of getting the elementID is wrong. What's the correct way to get the element ID?
It's because you're using vars for loop variables you always have i=4 and j=4 on click. Just replace those with let:
function clickable() {
var table = document.getElementById("mytable");
if (table != null) {
for (let i = 0; i < table.rows.length; i++) {
for (let j = 0; j < table.rows[i].cells.length; j++)
table.rows[i].cells[j].onclick = function () { colorChange(i, j); };
}
}
}
You don't need any of the i and j business. Just select the cell elements directly and loop through them to add an event listener, using querySelectorAll, as per the demo below.
N.B. You mentioned that you want to "change the background color of each cell depending on whether its value is >5 or below" ...but how are you defining the "value"? It's isn't clear. In the colorChange function, you try to test the value using the cell's "innerHTML", but your cells don't have any content anyway, so it would never work.
Therefore, for the purposes of the demo, I've assumed you intended to populate the cells with the values of i and k, and then interpret those as a single number when you do the test in colorChange.
Also <table border="1"> needed to be removed. You can't have a table directly within another table. And it's not necessary, anyway.
function createTable() {
document.body.innerHTML += '<table border="1" id="mytable"></table>';
for (var i = 0; i < 4; i++) {
document.getElementById("mytable").innerHTML += '<tr id="row' + i + '"></tr></table>';
for (var k = 0; k < 4; k++) {
document.getElementById("row" + i).innerHTML += '<td id=' + i + k + '>' + i + k + '</td>';
}
}
}
function clickable() {
var cells = document.querySelectorAll("#mytable td");
cells.forEach(function(cell) {
cell.addEventListener("click", colorChange);
});
}
function colorChange() {
console.log(this.innerHTML);
if (this.innerHTML > 5) {
this.style.backgroundColor = "green";
}
}
createTable();
clickable();
See https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll for documentation.
I think you're missing an opening curly bracket on the "j" loop of clickable
for (var j = 0; j < table.rows[i].cells.length; j++)
I also changed colorChange() to work with the event target:
function createTable() {
document.body.innerHTML += '<table border="1" id="mytable"></table>';
for (var i = 0; i < 4; i++) {
document.getElementById("mytable").innerHTML += '<table border="1"><tr id="row' + i + '"></tr></table>';
for (var k = 0; k < 4; k++) {
document.getElementById("row" + i).innerHTML += "<td id=" + i + k + ">" + Math.floor(Math.random() * 10) + "</td>";
}
}
}
function clickable() {
var table = document.getElementById("mytable");
if (table != null) {
for (var i = 0; i < table.rows.length; i++) {
for (var j = 0; j < table.rows[i].cells.length; j++) {
table.rows[i].cells[j].onclick = function(event) {
colorChange(event);
};
}
}
}
}
function colorChange(event) {
const cell = event.target;
if (cell.innerHTML > 5) {
cell.style.backgroundColor = "green";
}
}
<button onclick="createTable();clickable()">run</button>

Add a header row and a time column to a generated HTML table with jQuery

I have these two working JavaScript functions
https://github.com/cryptomanxxx/Random2DArrayPlusHtmlTable
https://cryptomanxxx.github.io/Random2DArrayPlusHtmlTable/
that 1) generates some random data 2) creates a HTML table for such data. There are two problems.
1) The HTML table column headings (the first row in the HTML table) are missing. Which is the simples way to add a row (should be the first row) with column headings to the HTML table? The column heading row should say something generic like this: variable 1, variable 2, variable 3 etc etc
2) The HTML table does not have a column with timestamps. A new column (first column) with timestamps would also be nice like: time 1, time 2, time 3 etc etc
It is obvious that I have not managed to understand how the code works because if I did it would be easy to modify the code. The complexity is overwhelming.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript" src="JavaS.js"></script>
<meta charset="utf-8" />
<style>
table {
border-collapse: collapse;
}
table,
td,
th {
border: 1px solid black;
}
</style>
</head>
<body>
<div id="div1">
</body>
<script> htmlTable(RandomArray(8, 4)); </script>
</html>
function RandomArray(rows, cols) {
var arr = [];
for (var i = 0; i < rows; i++) {
arr.push([]);
arr[i].push(new Array(cols));
for (var j = 0; j < cols; j++) {
arr[i][j] = Math.random();
}
}
console.log(arr);
return arr;
}
function htmlTable(d) {
var data = d;
var html = '<table><thead><tr></tr></thead><tbody>';
for (var i = 0, len = data.length; i < len; ++i) {
html += '<tr>';
for (var j = 0, rowLen = data[i].length; j < rowLen; ++j) {
html += '<td>' + data[i][j] + '</td>';
}
html += "</tr>";
}
$(html).appendTo('#div1') ;
}
Don't stress about the complexity, it gets easier the longer you play with it.
1) If you want column headers, that's what th tags are for... and they should go inside the thead tags you already have, like this:
var html = '<table><thead><tr><th>Timestamp</th><th>Variable 1</th><th>Variable 2</th><th>Variable 3</th><th>Variable 4</th></tr></thead><tbody>';
Read more about HTML tables here.
2) If you want an additional column, add in a value (a td - short for table data) before the loop that adds the randomize values
...
html += '<tr>';
html += '<td>' + new Date().getTime() + '</td>' <------ NEW CODE TO ADD ANOTHER VALUE
for (var j = 0, rowLen = data[i].length; j < rowLen; ++j) {
...
You can learn more about dates, both creating them and displaying them, here.
All said and done, your function would look like:
function htmlTable(d) {
var data = d;
var html = '<table><thead><tr><th>Timestamp</th><th>Variable 1</th><th>Variable 2</th><th>Variable 3</th><th>Variable 4</th></tr></thead><tbody>';
for (var i = 0, len = data.length; i < len; ++i) {
html += '<tr>';
html += '<td>' + new Date().getTime() + '</td>'
for (var j = 0, rowLen = data[i].length; j < rowLen; ++j) {
html += '<td>' + data[i][j] + '</td>';
}
html += "</tr>";
}
$(html).appendTo('#div1') ;
}

Putting image in table using innerHTML (Javascript / Html)

Alright, some information right off the bat, I have a table that is dynamically being created.
The table looks roughly like this :
|item__ | price | category | category | category | category | picture |
|chicken| $20 | _______ |_ ______ | _______ | _______ | 1000.png|
var array = csvpls();
var table = "<tr>";
for (var i = 0; i < array.length; i++) {
for (var j = 0; j < array[i].length; j++) {
if (j == 6) {
table += "<td>" + "<img src='CSV_Photos/" + array[i][j] +"'style ='width:500px;height:300px'>";
} else if {
table += "<td>" + array[i][j];
}
table += "<tr>";
table += "</tr>";
}
document.getElementById("Invtable").innerHTML = table;
This is the code that I have at the moment, where array is a 2D array. And every (6th column in the row, I want it to be an image) When runned, this does not display any table whatsoever.
In the code below
var array = csvpls();
var table = "<tr>";
for (var i = 0; i < array.length; i++) {
for (var j = 0; j < array[i].length; j++) {
table += "<td>" + array[i][j];
}
table += "<tr>";
table += "</tr>";
}
document.getElementById("Invtable").innerHTML = table;
Without the if statement and the additional img content, the table displays perfectly, but obviously 1000.png shows up instead of the actual image.
CSV_Photos is a folder where the image is stored at, essentially in the same folder. I don't know what is wrong, any help or leads are appreciated.
Edit: So the 2nd part of the code I have works perfectly, It generates a table for me. But at every 6th column of a row is a picture name (1000.png) and its in the folder CSV_Photo. I want it to no display as 1000.png, but instead the picture. The 1st section of code is my attempt to make it an image, but no table is created so I'm guessing there is something wrong with this line table += "" + <"img src= 'CSV_Photos/" + array[i][j] +"'style ='width:500px;height:300px'>";
I think there are several problems in your code that needs to be fixed :
You are not appending the td elements inside the tr but directly
inside the table, you need to move the line table += "<tr>";
before the nested loop.
And you are not specifying closing tags for <td> elements so when
you include the img tag it will mess up the layout.
Another thing just inverse the use of " and ' in your img tag
definition because HTML uses ".." to define attributes.
Here's how should be your code:
var array = csvpls();
var table = "<tr>";
for (var i = 0; i < array.length; i++) {
table += "<tr>";
for (var j = 0; j < array[i].length; j++) {
if (j == 6) {
table += "<td>" + '<img src="CSV_Photos/' + array[i][j] + '" style ="width:500px;height:300px"></td>';
} else if {
table += "<td>" + array[i][j] + "</td>";
}
}
table += "</tr>";
}
document.getElementById("Invtable").innerHTML = table;
Try:
var array = csvpls();
var table = "<table>";
for (var i = 0; i < array.length; i++) {
table += "<tr>";
for (var j = 0; j < array[i].length; j++) {
table += "<td>" + array[i][j];
}
table += "</tr>";
}
table += "</table>";
document.getElementById("Invtable").innerHTML = table;
If you wanted the image to be on the 2nd row, 3rd cell the condition should be:
if (i === 1 && j === 2) {...
If you want the whole 2nd row with the same image in each cell then it should be:
if (i === 1) {...
If you want a entire 3rd column to have the same image then it would be:
if (j === 2) {...
If it's a different image for every cell, then name each file by table coordinates like this...
img1-2.png
...then change the string that renders an image inside a cell as:
table += `<td><img src='http://imgh.us/img${i}-${j}.png' style ='width:50px;height:50px'></td>`
Or if I understand correctly, the array already has the filenames. If that's true, then the string should be...
table += `<td><img src='http://imgh.us/${array[i][j]}' style ='width:50px;height:50px'></td>`
... and the array would be something like this:
var array = [
['rt','AD','1000.png','uy','ii'],
['rt','AD','1001.png','uy','ii'],
['rt','AD','1002.png','uy','ii']
];
BTW, I had to do some changes to the code in order for it to work since it's only a partial code you provided, but the gist of it is the condition of course.
Also you'll notice the strange syntax of the strings, that's ES6 template literals or "strings on steroids".
Demo
var array = cvpls();
var table = ``;
for (var i = 0; i < array.length; i++) {
table += `<tr>`;
for (var j = 0; j < array[i].length; j++) {
if (i === 1 && j === 2) {
table += `<td><img src='http://imgh.us/statik.gif' style ='width:50px;height:50px'></td>`;
} else {
table += `<td>${array[i][j]}</td>`;
}
}
table += `</tr>`;
document.getElementById("Invtable").innerHTML = table;
}
function cvpls() {
return array = [
[4, 5, 6, 9, 2],
['img', 'img', 'img', 'img', 'img'],
['d', 'b', 'g', 'i', 'o']
];
}
td {
border: 1px solid black
}
<table id='Invtable'></table>

Dynamically assign unique id from var value in Javascript, jquery

In my program, I use javascript to generate a table which is then appended to the html document:
var html = "<table>";
for (var r = 0; r < rows; r++)
{
html += "<tr>";
for (var c = 0; c < cols; c++)
{
html += "<td class=\"covered\"><input type=\"image\" src=\"imageURL.com"/></td>";
}
html += "</tr>";
}
html += "</table>";
$(".gameboard").append(html);
I want each of the input elements to have a unique ID -- specifically a number. I was hoping to have a variable that is initialized to 1, which gets incremented each time a TD element is created. The value of this variable would be used as the input element ID. I haven't found any way to do this specifically. Thanks in advance!
Try this:
var html = "<table>";
var index=0;
for (var r = 0; r < rows; r++)
{
html += "<tr>";
for (var c = 0; c < cols; c++)
{
html += "<td class=\"covered\"><input id='img"+(index++)+"' type=\"image\" src=\"imageURL.com"/></td>";
}
html += "</tr>";
}
html += "</table>";
$(".gameboard").append(html);
Try to add a global variable let count and increment it in inner loop, like,
var html = "<table>";
var count=1;// use this variable in inner for loop and increment it by 1
for (var r = 0; r < rows; r++)
{
html += "<tr>";
for (var c = 0; c < cols; c++){
html += "<td class=\"covered\">\
<input id='"+(count++)+"' type=\"image\" src=\"imageURL.com\"/>\
</td>";
}
html += "</tr>";
}
html += "</table>";
$(".gameboard").append(html);
Try this code:
html += "<td id='td-" + c +"'class=\"covered\"><input value='td-" + c +"' type=\"image\" src=\"imageURL.com"/></td>";
use this
var ID= new Date().getTime();

Categories

Resources