Giving unique id to table cell - javascript

I have created a table.
I have text input where I type some text. It refers to some element with special values.
When I click a button the productname is added to the table (using insertCell()).
I want to give a unique id to every new table element.
function add1() {
var row, cell;
var productname = document.getElementById("produkt1").value; // text input
var table = document.getElementById("pos1"); // button near text input
if(productname === "Egg") {
p = ["Egg", "", 20, 10, 11, 101];
}
if(productname === "Milk") {
p = ["Milk", "", 30, 5, 12, 75];
}
row = table.insertRow(2);
var c_id = 0;
for (var i = 0; i < p.length ; i++) {
cell = row.insertCell(i);
cell.innerHTML = p[i];
for (var j = 0; j < 1 ; j++) {
cell.id = 'tdp1' + k_id;
c_id++;
}
} // It only works for one element, and the others have the same id as elements from row1
}

a. There seems to be a type in the line cell.id = 'tdp1' + k_id; It is supposed to be c_id instead of k_id
b. You do not need the second for loop for anything and just can remove it.
The following code gives me a new row with ids for each cell (tdp10 to tdp15)
function add1() {
var row, cell;
var productname = document.getElementById("produkt1").value; // text input
var table = document.getElementById("pos1"); // button near text input
if(productname === "Egg") {
p = ["Egg", "", 20, 10, 11, 101];
}
if(productname === "Milk") {
p = ["Milk", "", 30, 5, 12, 75];
}
row = table.insertRow(2);
var c_id = 0;
for(var i = 0; i < p.length ; i++){
cell = row.insertCell(i);
cell.innerHTML = p[i];
cell.id = 'tdp1' + c_id;
c_id++;
}
}

I found solution:
function add1() {
var row, cell;
var productname = document.getElementById("produkt1").value;
var table = document.getElementById("pos1");
if(productname === "Egg") {
p = ["Egg", "", 20, 10, 11, 101];
}
if(productname === "Milk") {
p = ["Milk", "", 30, 5, 12, 75];
}
var cells = document.getElementsByClassName("pos");
row = table.insertRow(2);
for(var i = 0; i < p.length ; i++){
cell = row.insertCell(i);
cell.innerHTML = p[i];
cell.className = "pos";
for(var j = 0; j < cells.length ; j++){
cell.id = 'tdp1' + j;
}
}
I gave created cell a className. It's working, but thank you for help. :)

Related

To create a custom table by getting values from a dynamicaly created table

what I want is on save click to show another table like below where the second column(Questions) has sub-columns depending maximum L value a row has:
unit Question
unit1 23(L1)
unit2 23(L3)
unit3 24(L3)
unit4 6(L2)
unit4 10(L4)
unit5 7(L1)
unit5 10(L6)
unit6 10(L2)
unit 7(L4)
var x = [];
function getval() {
var trs = $('#DyanmicTable3 tr:not(:first-child):not(:nth-last-child(2)):not(:last-child)');
var trs1 = $('#DyanmicTable3 tr:last-child');
var lastTotalElement = $('#DyanmicTable3 tr:nth-last-child(2)');
console.log(trs1);
for (let i = 2; i <= 7; i++) {
const total = Array.from(trs)
.reduce((acc, tr) => x.push(Number(tr.children[i].textContent)), 0);
;
}
console.log(JSON.stringify(x));
}
this is wt i got so far getting values in an array
function GenerateTable() {
var grid = new Array();
grid.push(["Unit", "Marks", "Bloom Level"]);
var tb = $('#DyanmicTable3:eq(0) tbody ');
tb.find("tr:not(:first-child):not(:nth-last-child(2)):not(:last-child)").each(function (index, element) {
var colValtst;
$(element).find('th:not(:first-child):not(:nth-last-child(2)):not(:last-child)').each(function (index, element) {
colValtst = $(element).text();
});
$(element).find('td').each(function (index, element) {
var colVal = $(element).text();
let y = $(element).index();
if (colVal != '') {
console.log(" Value in " + colValtst + " : " + colVal.trim() + " L" + y);
//add grid here
grid.push([colValtst, colVal.trim(), "L" + y]);
}
});
});
//Build an array containing Customer records.
// $('#save').attr('href', 'AddQuestions.aspx?val1=' + grid + '');
//Create a HTML Table element.
var table = document.createElement("TABLE");
table.border = "1";
//Get the count of columns.
var columnCount = grid[0].length;
//Add the header row.
var row = table.insertRow(-1);
for (var i = 0; i < columnCount; i++) {
var headerCell = document.createElement("TH");
headerCell.innerHTML = grid[0][i];
row.appendChild(headerCell);
}
//Add the data rows.
for (var i = 1; i < grid.length; i++) {
row = table.insertRow(-1);
for (var j = 0; j < columnCount; j++) {
var cell = row.insertCell(-1);
cell.innerHTML = grid[i][j];
}
}
var dvTable = document.getElementById("dvTable");
dvTable.innerHTML = "";
dvTable.appendChild(table);

to insert array values into specific table cells/columns

I'm creating a function that should take the data from an array (results) and put them into specific columns of the table. The array is divided with numbers that identify the column in which the following data should be entered.
Eg:
var results = [1, 'aaaaaa', 'bbb',2, 'ccc', 3, 'dddd', 'eeee', 4, 'fff'];
col 1: 'aaaaaa', 'bbb';
col 2: 'ccc'; etc.
I've tried it in many ways and I can not get it to work.
At the moment the code looks like this. I'm no sure how to do it:
var results = [1, 'aaaaaa','bbb',2, 'ccc', 3, 'dddd', 'eeee', 4, 'fff'];
var k = 0;
function populateTable(table, rows, cells, content) {
if (!table) table = document.createElement('table');
for (var i = 0; i < rows; ++i) {
var row = document.createElement('tr');
for (var j = 0; j < cells; ++j) {
row.appendChild(document.createElement('td'));
if (i > 0 && j == 0) {
row.cells[j].appendChild(document.createTextNode(content + 'PN'));
}
else if (i == 0 && j == 0) {
row.cells[j].appendChild(document.createTextNode(content + 'TYPE'));
}
else if (j > 0 && i == 0) {
row.cells[j].appendChild(document.createTextNode(content + 'LABLE ' + j));
}
else if (j > 0 && i > 0 && results[i] != k) {
row.cells[k].appendChild(document.createTextNode(content + results[i]));
}
}
table.appendChild(row);
k++;
}
return table;
}
function load() {
document.getElementById('tablearea')
.appendChild(populateTable(null, 9, 10, ""));
}
First format the results into something like:
{
1: ['aaaaaa', 'bbb'],
2: ['ccc'],
3: ['dddd', 'eeee'],
4: ['fff']
}
Then generate the table:
const results = [1, 'aaaaaa', 'bbb',2, 'ccc', 3, 'dddd', 'eeee', 4, 'fff', 5, 'ggg', 'hhhh', 'iiii'];
// First format the results
const formattedResults = {};
let columnIndex = 0;
results.forEach(elt => {
if (!isNaN(elt)) {
formattedResults[elt] = [];
columnIndex = elt;
} else {
formattedResults[columnIndex].push(elt);
}
});
// Then generate the table
const table = document.createElement('table');
const columnKeys = Object.keys(formattedResults);
const maxRows = Math.max(...columnKeys.map(key => formattedResults[key].length));
for (let i = 0; i < maxRows; i = i + 1) {
const tr = document.createElement('tr');
columnKeys.forEach(colKey => {
const td = document.createElement('td');
if (formattedResults[colKey][i] !== undefined) {
td.textContent = formattedResults[colKey][i];
tr.appendChild(td);
}
});
table.appendChild(tr);
}
document.getElementById('tableArea').appendChild(table);
<div id="tableArea"></div>

How to check value of table td?

I am trying to create mine field game. "I am very new to Js".
What I have done so far:
var level = prompt("Choose Level: easy, medium, hard");
if (level === "easy") {
level = 3;
} else if (level === "medium") {
level = 6;
} else if (level === "hard") {
level = 9;
}
var body = document.getElementsByTagName("body")[0];
var tbl = document.createElement("table");
var tblBody = document.createElement("tbody");
for (var i = 1; i <= 10; i++) {
var row = document.createElement("tr");
document.write("<br/>");
for (var x = 1; x <= 10; x++) {
var j = Math.floor(Math.random() * 12 + 1);
if (j < level) {
j = "mined";
} else {
j = "clear";
}
var cell = document.createElement("td");
var cellText = document.createTextNode(j + " ");
cell.appendChild(cellText);
row.appendChild(cell);
}
tblBody.appendChild(row);
}
tbl.appendChild(tblBody);
body.appendChild(tbl);
tbl.setAttribute("border", "2");
So I create here 2d table and enter 2 random values in rows and columns (mined or clear).
Where I am stuck is:
Check if td = mined it dies otherwise open the box(td) etc.
How do I assign value of td? I mean how can I check which value(mined/clear) there is in the td which is clicked?
Ps: Please don't write the whole code:) just show me the track please:)
Thnx for the answers!
Ok! I came this far.. But if I click on row it gives sometimes clear even if I click on mined row or vice versa!
// create the table
var body = document.getElementsByTagName("body")[0];
var tbl = document.createElement("table");
tbl.setAttribute('id','myTable');
var tblBody = document.createElement("tbody");
//Create 2d table with mined/clear
for(var i=1;i<=10;i++)
{
var row = document.createElement("tr");
document.write("<br/>" );
for(var x=1;x<=10;x++)
{
var j=Math.floor(Math.random()*12+1);
if(j<level)
{
j = "mined";
}
else{
j = "clear";
}
var cell = document.createElement("td");
var cellText = document.createTextNode(j + "");
cell.appendChild(cellText);
row.appendChild(cell);
}
tblBody.appendChild(row);
}
tbl.appendChild(tblBody);
body.appendChild(tbl);
tbl.setAttribute("border", "2");
//Check which row is clicked
window.onload = addRowHandlers;
function addRowHandlers() {
var table = document.getElementById("myTable");
var rows = table.getElementsByTagName("tr");
for (i = 0; i < rows.length; i++) {
var currentRow = table.rows[i];
var createClickHandler =
function(row)
{
return function() {
var cell = row.getElementsByTagName("td")[0];
var id = cell.innerHTML;
if(id === "mined")
{
alert("You died");
}else
{
alert("clear");
}
};
}
currentRow.onclick = createClickHandler(currentRow);
}
}
I think I do something wrong with giving the table id "myTable"..
Can you see it?
Thank you in advance!
So, the idea would be:
assign a click event to each td cell:
td.addEventListener('click', mycallback, false);
in the event handler (callback), check the content of the td:
function mycallback(e) { /*e.target is the td; check td.innerText;*/ }
Pedagogic resources:
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/td?redirectlocale=en-US&redirectslug=HTML%2FElement%2Ftd
https://developer.mozilla.org/en-US/docs/DOM/EventTarget.addEventListener
JavaScript, getting value of a td with id name

Putting random spaces in a dynamic grid

I have a list of words that dynamically generate a grid.
The problem is I need a 6x6 grid and if there is not enough words in the list to facilitate a 6x6 (12 words) then it won't.
How can I make it so it always produces a 6x6 grid, randomly generates positions for the words and fills the gaps with empty cells?
var listOfWords = ["mat", "cat", "dog", "pit", "pot", "fog"];
var shuffledWords = listOfWords.slice(0).sort(function() {
return 0.5 - Math.random();
}).slice(0, 6);
var tbl = document.createElement('table');
tbl.className = 'tablestyle';
var wordsPerRow = 2;
for (var i = 0; i < shuffledWords.length; i += wordsPerRow) {
var row = document.createElement('tr');
for (var j = i; j < i + wordsPerRow; ++j) {
var word = shuffledWords[j];
for (var k = 0; k < word.length; k++) {
var cell = document.createElement('td');
cell.textContent = word[k];
row.appendChild(cell);
}
}
tbl.appendChild(row);
}
document.body.appendChild(tbl);
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function loaded() {
var tbl = document.getElementById("tbl");
if(tbl != null) {
tbl.parentNode.removeChild(tbl);
}
var nrOfWordsToUse = Number(document.getElementById("howManyWords").value);
if(nrOfWordsToUse > 12 || nrOfWordsToUse < 0) {
alert("nrOfWordsToUse has to be between 0 and 12");
} else {
var initialListOfWords = ["mat", "cat", "dog", "pit", "pot", "fog", "aha", "beb", "pan", "pet", "pir", "pem"];
listOfWords = [];
for(var i = 0; i < nrOfWordsToUse; i++)
listOfWords[i] = initialListOfWords[i];
var positions = [];
for(var i = 0; i < 6; i++) {
positions[i] = ["", "", "", "", "", ""];
}
for(var i = 0; i < listOfWords.length; i++) {
var y = number0to5();
var x = number0or3();
if(positions[y][x] == "") {
positions[y][x] = listOfWords[i].charAt(0);
positions[y][x + 1] = listOfWords[i].charAt(1);
positions[y][x + 2] = listOfWords[i].charAt(2);
} else {
i--;
}
}
var table = document.createElement("table");
table.id = "tbl";
document.body.appendChild(table);
for(var i = 0; i < positions.length; i++) {
var row = table.insertRow(-1);
for(var j = 0; j < positions[i].length; j++) {
var cell = row.insertCell(-1);
cell.innerHTML = positions[i][j];
}
}
}
alert("end");
}
function number0to5() {
return Math.floor(Math.random() * 6);
}
function number0or3() {
return Math.random() > 0.5 ? 0 : 3;
}
</script>
</head>
<body>
<input id="howManyWords" value="6" /><input type="button" onclick="loaded()" value ="doIt"/>
</body>
</html>
Here is a fiddle: http://jsfiddle.net/dpbzq/12/
About your request to help you build in my code into yours:
I made a new fiddle: http://jsfiddle.net/uv74h/2/
As you can see, it is a function: rndSpaces. It takes 1 parameter; an array of 3-letter words, with a maximum of 12 words. They don't have to be pre-shuffled; the function will shuffle them. The function will try to find a table with id == "myTable". If it doesn't find the table it creates a table and appends it to a div with id == "myDiv" (There is one line commented out; if you want to append it to the body, uncomment that line and comment out the line that appends the table to the div). The function clears everything in the table, creates a 6x6 grid and fills it with the words. I gave the table, rows and cells a css style (tablestyle, myRow and myCell).
this is an example of the function getting called:
rndSpaces(["pim", "pam", "pet", "rol", "fik", "fak", "ral"]);​
Updated JSFiddle
I added:
while(listOfWords.length < 6)
listOfWords.push(" ");
So if there are not enough words, it appends the array with empty 'words' (3 spaces) and that gets shuffled, which results in random blank spaces
EDIT
JSFiddle with 12 words
EDIT2
I think this is what you want:
JSFiddle with 6 words, filled with spaces

JQuery - generating a grid from a list of words

Currently this script takes the words from the list and generates a grid, giving the words random positions each time. When the words are generated I want them to be split into individual characters, into cells next to each other so the word still makes sense - how do I do this?
var listOfWords = ["mat", "cat", "dog", "pit", "pot", "fog", "log", "pan", "can", "man", ];
var shuffledWords = listOfWords.slice(0, 12);
shuffledWords.sort(function () {
return 0.5 - Math.random();
});
var table = $('<table class="tablestyle">');
var rows = 6;
var cols = 2;
var tr;
var index;
for (var row = 0; row < rows; row++) {
tr = $('<tr>');
for (var col = 0; col < cols; col++) {
index = (row * cols) + col;
$('<td>').text(shuffledWords[index]).appendTo(tr);
}
tr.appendTo(table);
}
table.appendTo('body');
$('<table>' + innerTable + '</table>').appendTo('body');
Am I right to assume that for each word you want a new row, and for letter in the word you want a new cell?
Try this:
var listOfWords = ["mat", "cat", "dog", "pit", "pot", "fog", "log", "pan", "can", "man", ];
var shuffledWords = listOfWords.slice(0, 12);
shuffledWords.sort(function () {
return 0.5 - Math.random();
});
var tbl = document.createElement('table');
tbl.style.border='solid 1px silver';
for (var i = 0; i < shuffledWords.length; i++)
{
var word = shuffledWords[i];
var row = document.createElement('tr');
for (var j = 0; j < word.length; j++)
{
var cell = document.createElement('td');
cell.style.border='solid 1px silver';
cell.innerText = word[j];
// IF FIREFOX USE cell.textContent = word[j]; INSTEAD
row.appendChild(cell);
}
tbl.appendChild(row);
}
document.body.appendChild(tbl);
http://jsfiddle.net/YJjkB/1/

Categories