I need some help, what should I do so that all the rows have each one a different id for example:introdu1,introdu2,introdu3
var perrow = 1;
array.forEach((value, i) => {
myTable += `<td id="ore">${value}</td>`;
myTable += `<td id="introdu" > </td>`;
var next = i + 1;
if (next%perrow==0 && next!=array.length) { myTable += "</tr><tr>"; }
});
It is very easy you can use ${variable} like you do in ${value}
let array = ['r','4','6'];
let myTable = "";
var perrow = 1;
array.forEach((value, i) => {
var next = i + 1;
myTable += `<td id="ore${next}">${value}</td>`;
myTable += `<td id="introdu${next}" > </td>`;
if (next%perrow==0 && next!=array.length) { myTable += "</tr><tr>"; }
});
console.log(myTable);
td {
background : red;
}
Use a dynamically generated ID:
var perrow = 1;
var id = 1;
array.forEach((value, i) => {
myTable += `<td id="ore${id}">${value}</td>`;
myTable += `<td id="introdu${id++}" > </td>`;
var next = i + 1;
if (next % perrow == 0 && next != array.length) {
myTable += "</tr><tr>";
}
});
Related
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;
}
I have 49 cells (7x7 rows/cols), and I'm trying to create one cell out of the 49 cells to be unique, as you can see when you run the snippet, the 49 cells have random numbers between 50 to 500, and one of these cells have Red color.
The problem I'm struggling with, I want that one cell to have Symbol (marking plate) like S or D for example instead of number, How i can achieve that?
var isCol = 0;
var board = [];
for (r = 0; r < 7; r++) {
var line = [];
for (c = 0; c < 7; c++) {
line.push(RandomGenerator(50, 500));
}
board.push(line);
}
function prs(c, r) {
showTable(c, r);
isCol = (isCol + 1) % 2;
}
function toColor(col, row, chosen_col, chosen_row) {
var ret = false;
switch (isCol) {
case 0:
if (row == chosen_row) {
ret = true;
}
break;
case 1:
if (col == chosen_col) {
ret = true;
}
break;
}
return ret;
}
function showTable(chosen_col, chosen_row) {
var str = "";
str += "<table border=1>";
for (row = 0; row < 7; row++) {
str += "<tr>";
for (col = 0; col < 7; col++) {
str += "<td onclick='prs(" + col + "," + row + ")'";
if (toColor(col, row, chosen_col, chosen_row)) {
str += " class='grn' ";
}
str += ">";
str += board[row][col];
str += "</td>";
}
str += "</tr>";
}
str += "</table>";
document.getElementById("ff").innerHTML = str;
}
function RandomGenerator(min, max) {
return Math.floor(Math.random() * (max - min) + min);
}
showTable(-1);
var getUnique = function(){
var tdElements = document.querySelectorAll('#ff td');
tdElements[
RandomGenerator(0, tdElements.length)
].classList.add('uniqueCell')
};
getUnique();
td{
border:2px solid black;
width:10px;
height:10px;
}
td:hover{background-color:lightgreen;}
.grn{
background-color:green;
color:white;
}
.uniqueCell {
background-color: tomato;
}
<div id="ff"></div>
It seems pretty easy as you have a class (uniqueCell) in the element. You can simply target the cell with the class (uniqueCell) and set the innerText or textContent property:
document.querySelector('.uniqueCell').textContent = 'S';
var isCol = 0;
var board = [];
for (r = 0; r < 7; r++) {
var line = [];
for (c = 0; c < 7; c++) {
line.push(RandomGenerator(50, 500));
}
board.push(line);
}
function prs(curr, c, r) {
showTable(curr, c, r);
isCol = (isCol + 1) % 2;
}
function toColor(col, row, chosen_col, chosen_row) {
var ret = false;
switch (isCol) {
case 0:
if (row == chosen_row) {
ret = true;
}
break;
case 1:
if (col == chosen_col) {
ret = true;
}
break;
}
return ret;
}
function showTable(c, chosen_col, chosen_row) {
var str = "";
str += "<table border=1>";
for (row = 0; row < 7; row++) {
str += "<tr>";
for (let col = 0; col < 7; col++) {
str += "<td onclick='prs(this, " + col + "," + row + ")'";
if (toColor(col, row, chosen_col, chosen_row)) {
if(c.textContent == board[row][col]){
str += " class=uniqueCell";
}
else str += " class='grn' ";
}
str += ">";
if(c.textContent == board[row][col]){
str += 'S';
}
else str += board[row][col];
str += "</td>";
}
str += "</tr>";
}
str += "</table>";
document.getElementById("ff").innerHTML = str;
}
function RandomGenerator(min, max) {
return Math.floor(Math.random() * (max - min) + min);
}
showTable(-1);
var getUnique = function(){
var tdElements = document.querySelectorAll('#ff td');
tdElements[
RandomGenerator(0, tdElements.length)
].classList.add('uniqueCell');
// update the text of the cell using the class
document.querySelector('.uniqueCell').textContent = 'S';
};
getUnique();
td{
border:2px solid black;
width:10px;
height:10px;
text-align: center;
}
td:hover{background-color:lightgreen;}
.grn{
background-color:green;
color:white;
}
.uniqueCell {
background-color: tomato;
}
<div id="ff"></div>
I have a random grid generator that asks how big you want the grid. If you input 5 it will produce a 5x5 grid with random numbers in it, or a 10x10 grid with random numbers etc.
I now need to take those random numbers once the grid is produced and display the average of the random numbers. I can't seem to get this part to work, because there are different numbers each time you generate a new grid.
var button = document.getElementById('gridSize');
button.onclick = function(e) {
result = document.getElementById('wrapper');
num = parseInt(document.getElementById('grid').value);
var str = "<table border='2'>";
for (row = 0; row < num; row++) {
str += "<tr>";
for (col = 0; col < num; col++) {
var randNumber = Math.floor(Math.random() * 100) + 1;
if (randNumber % 3 === 0) {
str += '<td style="background: red;">';
}
else if (randNumber % 2 === 0 && !randNumber % 3 === 0) {
str += '<td style="background: blue;">';
}
else {
str += "<td>";
}
str += randNumber + "</td>";
}
str += "</tr>";
}
str = str + "</table>";
result.innerHTML = str;
}
<form name="tablegen">
<input type="text" name="grid" id="grid"/>
<input name="generate" id="gridSize" type="button" value="Generate Grid!" onclick='createTable();'/>
</form>
<div id="wrapper"></div>
This is my code and I just can't seem to figure out how to go about this.
Here is a simple way, just accumulate the randNumber you calculated, then divide by the total number of cells.
var button = document.getElementById('gridSize');
button.onclick = function(e) {
result = document.getElementById('wrapper');
num = parseInt(document.getElementById('grid').value);
var avg = 0;
var str = "<table border='2'>";
for (row = 0; row < num; row++) {
str += "<tr>";
for (col = 0; col < num; col++) {
var randNumber = Math.floor(Math.random() * 100) + 1;
avg += randNumber;
if (randNumber % 3 === 0) {
str += '<td style="background: red;">';
}
else if (randNumber % 2 === 0 && !randNumber % 3 === 0) {
str += '<td style="background: blue;">';
}
else {
str += "<td>";
}
str += randNumber + "</td>";
}
str += "</tr>";
}
avg /= num*num;
str = str + "</table>" + "<span>Average is " + avg + "</span>";
result.innerHTML = str;
}
<form name="tablegen">
<input type="text" name="grid" id="grid"/>
<input name="generate" id="gridSize" type="button" value="Generate Grid!" onclick='createTable();'/>
</form>
<div id="wrapper"></div>
A couple of additions to what you gave us to start with.
var button = document.getElementById('gridSize');
var total = 0;
var divisor = 0;
button.onclick = function(e) {
result = document.getElementById('wrapper');
num = parseInt(document.getElementById('grid').value);
var str = "<table border='2'>";
for (row = 0; row < num; row++) {
str += "<tr>";
for (col = 0; col < num; col++) {
var randNumber = Math.floor(Math.random() * 100) + 1;
total = total+randNumber;
++divisor;
if (randNumber % 3 === 0) {
str += '<td style="background: red;">';
}
else if (randNumber % 2 === 0 && !randNumber % 3 === 0) {
str += '<td style="background: blue;">';
}
else {
str += "<td>";
}
str += randNumber + "</td>";
}
str += "</tr>";
}
str = str + "</table>";
result.innerHTML = str;
var average = total / divisor;
var averageSpan = document.getElementById('average');
averageSpan.innerText = average;
}
<form name="tablegen">
<input type="text" name="grid" id="grid"/>
<input name="generate" id="gridSize" type="button" value="Generate Grid!" onclick='createTable();'/>
</form>
Average: <span id="average"></span>
<div id="wrapper"></div>
Also a fiddle: https://jsfiddle.net/xpvt214o/775850/
Well, create a variable where you keep summing all generated random numbers.
At the end, get that number and divide by the area of the grid (the number user typed * the number user typed num*num)
Like below:
var button = document.getElementById('gridSize');
button.onclick = function(e) {
var total = 0;
result = document.getElementById('wrapper');
num = parseInt(document.getElementById('grid').value);
var str = "<table border='2'>";
for (row = 0; row < num; row++) {
str += "<tr>";
for (col = 0; col < num; col++) {
var randNumber = Math.floor(Math.random() * 100) + 1;
if (randNumber % 3 === 0) {
str += '<td style="background: red;">';
}
else if (randNumber % 2 === 0 && !randNumber % 3 === 0) {
str += '<td style="background: blue;">';
}
else {
str += "<td>";
}
total += parseInt(randNumber);
str += randNumber + "</td>";
}
str += "</tr>";
}
str = str + "</table>";
result.innerHTML = str;
console.log("Avg.: ", total/(num*num) || 0)
}
<form name="tablegen">
<input type="text" name="grid" id="grid"/>
<input name="generate" id="gridSize" type="button" value="Generate Grid!" onclick='createTable();'/>
</form>
<div id="wrapper"></div>
There are already some good answers. Here is a different approach. I also "cleaned up" the HTML and code a bit:
let button = document.getElementById("generatorButton");
button.onclick = function(e) {
document.getElementById("grid").innerHTML = createGrid();
document.getElementById("full-average").innerText = getGridAverage();
document.getElementById("mod3-average").innerText = getGridAverage(".mod3");
document.getElementById("mod2-average").innerText = getGridAverage(".mod2");
}
function createGrid()
{
gridSize = parseInt(document.getElementById('gridSize').value);
let str = "<table border='2'>";
for (let row = 0; row < gridSize; row++) {
str += "<tr>";
for (let col = 0; col < gridSize; col++) {
var randNumber = Math.floor(Math.random() * 100) + 1;
if (randNumber % 3 === 0) {
str += '<td class="mod3">';
}
else if (randNumber % 2 === 0) {
str += '<td class="mod2">';
}
else {
str += "<td>";
}
str += randNumber + "</td>";
}
str += "</tr>";
}
str = str + "</table>";
return str;
}
function getGridAverage(cssClass)
{
if (cssClass == undefined) cssClass = "";
let cells = document.querySelectorAll("#grid td" + cssClass);
if (cells.length > 0)
{
let sum = 0;
for (const cell of cells)
{
sum += parseInt(cell.innerHTML);
}
return sum / cells.length;
}
else
return 0;
}
.mod3 {
background-color: red;
}
.mod2 {
background-color: blue;
}
<form name="tablegen">
<input type="text" id="gridSize" placeholder="Enter grid size (e.g.: 5)" />
<input type="button" id="generatorButton" value="Generate Grid!" />
</form>
<div id="grid"></div>
<div>Full Average:<span id="full-average">n/a</span></div>
<div>Mod3 (red) Average:<span id="mod3-average">n/a</span></div>
<div>Mod2 (blue) Average:<span id="mod2-average">n/a</span></div>
I have dynamically created rows and columns with jQuery. Can anyone help me on how to select a random column from each row? So far here is how my code looks like;
$(document).ready(function(){
var canva = $("#board");
var gameHolder = "<div class='gHolder'>";
var rows = 7;
var cols = 10;
function boardSetUp(){
for(var i = 0; i < rows; i++){
var row = "<div class='row'>";
for(var j = 0; j < cols; j++){
var col = "<li class='col'>";
col += "</li>";
row += col;
}
row += "</div>";
gameHolder += row;
}
gameHolder += "</div>";
canva.html(gameHolder);
}
boardSetUp();
})
You can use a comibnation of Math.floor() and Math.random() to get an integer between 1 and the amount of columns (x) per row.
Math.floor (Math.random () * x) + 1
I simplified your given example and added a funtion to select one random column per row. For this example I dynamically add a class for each selected column.
$(document).ready (function () {
var rows = 7;
var cols = 10;
var gameHolder = '';
for (var i = 0; i < rows; i++) {
gameHolder += '<div class="row">';
for(var j = 0; j < cols; j++)
gameHolder += '<div class="col"></div>';
gameHolder += '</div>';
}
$("#board").html(gameHolder);
})
function select_cols () {
var canvas = $("#board");
//reset all columns
$('.col').removeClass ('selected');
//loop through every row
canvas.find ('.row').each (function (i) {
//count columns and select random one
var count = $(this).find ('.col').size (); // $(this) is the current row
var selected = Math.floor (Math.random () * count) + 1;
//get your selected column-element
var column = $(this).find ('.col:nth-child(' + selected + ')') // :nth-child(x) is a css-selector
//do something with it. for example add a class
column.addClass ('selected');
});
}
#board {
border: 1px solid #999;
}
.row {
display: flex;
}
.col {
flex-grow: 1;
height: 10px;
border: 1px solid #999;
}
.selected {
background-color: #958;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="board"></div>
<br>
<button onclick="select_cols ();">select random columns</button>
I see that you're asking for a random column for each row, but if you'd like just a random position on the game board, you could do something like this:
$(document).ready(function(){
var canva = $("#board");
var gameHolder = "<div class='gHolder'>";
var rows = 7;
var cols = 10;
function boardSetUp(){
for(var i = 0; i < rows; i++){
var row = "<div class='row'>";
for(var j = 0; j < cols; j++){
var col = "<li class='col' id='" + i + "-" + j + "'>";
col += "</li>";
row += col;
}
row += "</div>";
gameHolder += row;
}
gameHolder += "</div>";
canva.html(gameHolder);
}
boardSetUp();
function selectRandomLocation(){
var pos = $('#' + Math.floor(Math.random() * rows) + '-' + Math.floor(Math.random() * cols));
return pos;
}
})
you can use foreach and random ,
try :
var j = 0;
$("row").each(function(){
random_col = Math.floor(Math.random() * 10);
var i = 0;
$("li").each(function(){
if(random_col == i)
/* $(this) = your random col */
alert("the random col is a number "+i+" for col number "+j);
i++;
});
j++;
});
My JSON Array containing date and key-value pairs of alphabets. I need columns as date values and rows heading as Alphabets.
{
"error":0,
"data":[
{
"date":"2017-12-01",
"A":1,
"B":2
},
{
"date":"2017-12-02",
"A":2,
"B":3
}
]
}
I want to create table as given below
Alpha 2017-12-01 2017-12-02
A 1 2
B 2 3
My HTML Code containing datatable for table formatting:
<table id="report" class="table table-striped table-bordered">
<thead>
<tr>
<th>Alpha</th>
</tr>
</thead>
<tbody></tbody>
</table>
And JQuery ajax get response that calls the API:
$.ajax({
url: 'userData/01/2018',
success: function(response) {
let reportData = response.data;
let i = 0;
let j = 1;
let k = 0;
let table = document.getElementById('report');
let tr = table.tHead.children[0];
reportData.forEach(function(data) {
let row = table.insertRow(j);
if (i == 0) {
let th = document.createElement('th');
th.innerHTML = data.date;
tr.appendChild(th);
}
if (k == 0) {
let keys = Object.keys(data);
for (let p = 1; p < keys.length; p++) {
let cell = row.insertCell(k);
cell.innerHTML = keys[p];
for (let q = 1; q < keys.length; q++) {}
}
}
});
}
});
I am able to insert headers as table columns but facing an issue in data insertion.
slight changes in your json string,
HTML:
<table id="report"></table>
JavaScript:
var jsonString = '{"error": 0,"Alpha": [{"date": "2017-12-01","A": 1,"B": 2},{"date": "2017-12-02","A": 2,"B": 3}]}';
var s = '';
$.each(JSON.parse(jsonString), function(i, j) {
if (i == 'Alpha') {
s += '<thead><th>' + i + '</th>';
$.each(j, function(k, val) {
s += '<th>' + val.date + '</th>';
});
s += '</thead>';
$('#report').html(s);
for (var l = 0; j.length; l++) {
if (l == 0) {
s = '<tbody><tr><td> ' + Object.keys(j[l])[l + 1] + ' </td>';
s += '<td> ' + j[l].A + ' </td><td>' + j[l].B + '</td></tr>';
$('#report').append(s);
} else {
s = '<tr><td>' + Object.keys(j[l])[l + 1] + '</td><td>' + j[l].A + '</td><td>' + j[l].B + '</td></tr>';
$('#report').append(s);
}
s += '</tbody>';
}
}
});
For reference - https://jsfiddle.net/zvxqf9mz/