Putting random spaces in a dynamic grid - javascript

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

Related

Editable Table in Flask/HTML

I am trying to create an excel-like table to update and log things on the go.
I have found this javascript:
function init()
{
var tables = document.getElementsByClassName("editabletable");
var i;
for (i = 0; i < tables.length; i++)
{
makeTableEditable(tables[i]);
}
}
function makeTableEditable(table)
{
var rows = table.rows;
var r;
for (r = 0; r < rows.length; r++)
{
var cols = rows[r].cells;
var c;
for (c = 0; c < cols.length; c++)
{
var cell = cols[c];
var listener = makeEditListener(table, r, c);
cell.addEventListener("input", listener, false);
}
}
}
function makeEditListener(table, row, col)
{
return function(event)
{
var cell = getCellElement(table, row, col);
var text = cell.innerHTML.replace(/<br>$/, '');
var items = split(text);
if (items.length === 1)
{
// Text is a single element, so do nothing.
// Without this each keypress resets the focus.
return;
}
var i;
var r = row;
var c = col;
for (i = 0; i < items.length && r < table.rows.length; i++)
{
cell = getCellElement(table, r, c);
cell.innerHTML = items[i]; // doesn't escape HTML
c++;
if (c === table.rows[r].cells.length)
{
r++;
c = 0;
}
}
cell.focus();
};
}
function getCellElement(table, row, col)
{
// assume each cell contains a div with the text
return table.rows[row].cells[col].firstChild;
}
function split(str)
{
// use comma and whitespace as delimiters
return str.split(/,|\s|<br>/);
}
window.onload = init;
And it seems like it will work well in saving and keeping the edits in the table.
The issue is, however, that I am using pycharms and - unfortunately - cannot use a js file within mine.
Is there a way to convert this to Python, or a way to code a table within Python?

Javascript code that should make a table and run on page load [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
Javascript should run when the page loads, create a table with 10 rows and 10 columns and adds it to div "funky", the cells of the table should contain the text "N M" where N is the minumum of the row and column index and M is the maximum of the row and column index,cells in even numbered columns should have the text colour purple. here are my javascript and html codes
function go() {
var ROWS = 10;
var COLS = 10;
var out = document.getElementsByClassName("funky");
var table = document.createElement("table");
table.border = 1;
for (var i = 0; i <= ROWS; i += 1) {
var row = document.createElement("row");
if (i == 2) {
row.Fontweight = "bold";
}
for (var j = 0; j < COLS; j += 2) {
var col = document.createElement("cell");
col.innerHTML = i + " " + j;
if (j / 2 === 0) {
col.style.color = "purple";
}
row.appendChild(col);
}
table.appendChild(row);
document.getElementsByClassName("table");
}
}
onload = go();
<html>
<head>
<title>Question 2</title>
<script src="question2.js" type="text/javascript"></script>
<head>
<body>
<div class="funky"></div>
</body>
<html>
Replace HTML Code To :
<html>
<head>
<title>Question 2</title>
<script src="question2.js" type="text/javascript"></script>
</head>
<body onload="javascript:go();">
<div class="funky"></div>
</body>
</html>
Replace JS Code To :
function go() {
var ROWS = 10;
var COLS = 10;
var out = document.getElementsByClassName("funky")[0];
var table = document.createElement("table");
table.style.border = "1px solid #000";
table.style.borderCollapse = "collapse";
for (var i = 0; i <= ROWS; i += 1) {
var row = document.createElement("tr");
if (i == 2) {
row.style.fontWeight = "bold";
}
for (var j = 0; j < COLS; j += 1) {
var col = document.createElement("td");
col.innerHTML = i + " " + j;
if (j % 2 === 0) {
col.style.color = "purple";
}
row.appendChild(col);
}
table.appendChild(row);
}
out.appendChild(table);
}
You need to use MOD Operator to understand is it even or not. You need to use style property before using border property.
You have several mistakes in your code.
When you use getElementsByClassName you need to access them by
index like this
var out = document.getElementsByClassName("funky")[0];
You need to append table after creating it to div then it will be
show on page.
You need to create tr instead of row and td instead of cell.
function go() {
var ROWS = 10;
var COLS = 10;
var out = document.getElementsByClassName("funky")[0];
var table = document.createElement("table");
table.border = 1;
for (var i = 0; i <= ROWS; i ++) {
var row = document.createElement("tr");
if (i == 2) {
row.style.fontWeight = "bold";
}
for (var j = 0; j < COLS; j += 2) {
var col = document.createElement("td");
col.innerHTML = i + " " + j;
if (j / 2 === 0) {
col.style.color = "purple";
}
row.appendChild(col);
}
table.appendChild(row);
document.getElementsByClassName("table");
}
out.appendChild(table);
}

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

Injecting table into specific class

When I generate this table it is generated after the rest of the code is executed.
I want to be able to generate the code into a specific class like ".container".
How would I do this?
var listOfWords = [];
var rndWord = [];
var counter = 0;
var ul = document.getElementById("wordlist");
var i;
for (i = 0; i < ul.children.length; ++i) {
listOfWords.push({
"name": ul.children[i].getAttribute("data-word"),
"pic": ul.children[i].getAttribute("data-pic"),
"audio": ul.children[i].getAttribute("data-audio")
});
}
var chosenWords = [];
var copylist = listOfWords.slice();
for (var x = 0; x < 6; x++) {
var rand = Math.floor(Math.random() * (copylist.length));
chosenWords.push(copylist[rand].name);
copylist.splice(rand, 1);
if (chosenWords.length < 12) {
chosenWords.push(' ');
}
}
var shuffledWords = [];
shuffledWords = chosenWords.sort(function() {
return 0.5 - Math.random()
});
var guesses = {};
var tbl = document.createElement('table');
tbl.className = 'tablestyle';
var wordsPerRow = 2;
for (var i = 0; i < shuffledWords.length - 1; i += wordsPerRow) {
var row = document.createElement('tr');
for (var j = i; j < i + wordsPerRow; ++j) {
var word = shuffledWords[j];
guesses[word] = [];
for (var k = 0; k < word.length; ++k) {
var cell = document.createElement('td');
$(cell).addClass('drop-box').attr('data-word', word).attr('data-letter', word[k]);
cell.textContent = word[k];
row.appendChild(cell);
}
}
tbl.appendChild(row);
}
document.body.appendChild(tbl);
I thought changing the bottom line of this code from
document.body.appendChild(tbl);
to
document.container.appendChild(tbl);
would do it but it didn't.
Does anyone know how to put this table into container?
If you want to add the table to an element with a specific css class, you can do the following.
$(".container").append(tbl);

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