Crosswords puzzle in html - javascript

This little puzzle only accept lowercases.
How do I make it accept both upper and lowercase letters, please?
Or at least make an alert for the user to deactivate the caps lock?
HTML
<body onload="initializeScreen()">
<table id="puzzle">
</table>
<input class="butt" type="submit" value="Check" onclick="checkClicked()">
JS
//Loads the Crossword
function initializeScreen(){
var puzzleTable = document.getElementById("puzzle");
puzzleArrayData = preparepuzzleArray();
for ( var i = 0; i < puzzleArrayData.length ; i++ ) {
var row = puzzleTable.insertRow(-1);
var rowData = puzzleArrayData[i];
for(var j = 0 ; j < rowData.length ; j++){
var cell = row.insertCell(-1);
if(rowData[j] != 0){
var txtID = String('txt' + '_' + i + '_' + j);
cell.innerHTML = '<input type="text" class="inputBox" maxlength="1" style="text-transform: uppercase" ' + 'id="' + txtID + '" onfocus="textInputFocus(' + "'" + txtID + "'"+ ')">';
}
}
}
addHint();
}
//Returns Array
function preparepuzzleArray(){
var items = [[0, 'f', 0],
['r', 'u', 'n'],
[0, 'n', 0],
];
return items;
}
//Check button
function checkClicked(){
for ( var i = 0; i < puzzleArrayData.length ; i++ ) {
var rowData = puzzleArrayData[i];
for(var j = 0 ; j < rowData.length ; j++){
if(rowData[j] != 0){
var selectedInputTextElement = document.getElementById('txt' + '_' + i + '_' + j);
if(selectedInputTextElement.value != puzzleArrayData[i][j]){
selectedInputTextElement.style.backgroundColor = 'pink';
}else{
selectedInputTextElement.style.backgroundColor = 'lightgreen';
}
}
}
}
}
I also want to make the focus to go automatically to the next input once the previous input has reached its maxlength value? Is that possible?

In terms of testing for the caps lock you could say
const puzzle = document.getElementById('#puzzle');
puzzle.addEventListener('keyup', function (event) {
let caps = event.getModifierState('CapsLock');
if(caps){
alert("Please turn off caps lock etc..")
}
})

Related

Creating M*N table and export and download excel file with java script in html page

Is there a way that the following script after creating the table (N * M) can finally receive and download Excel output from it. Of course, I mean without using Excel software DLLs.
The script for creating the table is as follows (Generates the script below the table but I do not know how to convert it to Excel.) :
var rows = prompt("How many rows for your multiplication table?");
var cols = prompt("How many columns for your multiplication table?");
if (rows == "" || rows == null)
rows = 10;
if (cols == "" || cols == null)
cols = 10;
createTable(rows, cols);
function createTable(rows, cols) {
var j = 1;
var output = "<table border='1' width='500' cellspacing='0'cellpadding='5'>";
for (i = 1; i <= rows; i++) {
output = output + "<tr>";
while (j <= cols) {
output = output + "<td>" + i * j + "</td>";
j = j + 1;
}
output = output + "</tr>";
j = 1;
}
output = output + "</table>";
document.write(output);
}
A simple solution would be just encode the table and save as excel -
var rows = prompt("How many rows for your multiplication table?");
var cols = prompt("How many columns for your multiplication table?");
if (rows == "" || rows == null)
rows = 10;
if (cols == "" || cols == null)
cols = 10;
createTable(rows, cols);
function createTable(rows, cols) {
var j = 1;
var output = "<table border='1' width='500' cellspacing='0'cellpadding='5'>";
for (i = 1; i <= rows; i++) {
output = output + "<tr>";
while (j <= cols) {
output = output + "<td>" + i * j + "</td>";
j = j + 1;
}
output = output + "</tr>";
j = 1;
}
output = output + "</table>";
document.write(output);
const html = document.getElementsByTagName('table')[0].outerHTML;
var url = 'data:application/vnd.ms-excel,' + encodeURIComponent(html);
location.href = url;
}
JSFiddle
Try using function exportToExcel below. It takes tableString string & downloads export.xls file with this table.
var rows = prompt("How many rows for your multiplication table?");
var cols = prompt("How many columns for your multiplication table?");
if (rows == "" || rows == null)
rows = 10;
if (cols == "" || cols == null)
cols = 10;
function createTable(rows, cols) {
var j = 1;
var output = "<table border='1' width='500' cellspacing='0'cellpadding='5'>";
for (i = 1; i <= rows; i++) {
output = output + "<tr>";
while (j <= cols) {
output = output + "<td>" + i * j + "</td>";
j = j + 1;
}
output = output + "</tr>";
j = 1;
}
output = output + "</table>";
return output;
}
/*
* Export table string as excel
*/
function exportToExcel(tableString){
var uri = 'data:application/vnd.ms-excel;base64,';
var template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table>{table}</table></body></html>';
var base64 = function(s) {
return window.btoa(unescape(encodeURIComponent(s)))
};
var format = function(s, c) {
return s.replace(/{(\w+)}/g, function(m, p) {
return c[p];
})
};
var ctx = {
worksheet : 'Worksheet',
table : tableString
}
var link = document.createElement("a");
link.download = "export.xls";
link.href = uri + base64(format(template, ctx));
link.click();
}
// create table as a string
const tableString = createTable();
// export table string to excel (be sure that popups are allowed in your browser)
exportToExcel(tableString)

Default tab active not working in jquery and javascript

I have a table to show with tabs on it. i have implemented it.
But having issue in when I reload the page of this table view, i need to make the tab 1 as active as defult. I have added the code, but it is not working
below is the page code
function showDataInTable(data) {
var wrapper = $("<div></div>");
var wrapperUL = $("<ul class='nav nav-tabs'></ul>");
var tabContentDiv = $("<div class='tab-content'></div>");
var tab;
for (var i = 0; i < data.length; i++ ) {
tab = data[i];
wrapperUL.append('<li role="sheet_name" class="tab-li' + i + '"><a href="#' + i +
'" aria-controls="' + i + '" role="tab" data-toggle="tab">' + tab.sheetName +
'</a></li>');
var div = $('<div role="tabpanel" class="tab-pane" id="' + i + '" sheet_name="' + tab.sheetName + '"></div>');
var table = $('<table class="table table-condensed table-bordered table-hover"><thead><tr><th>#</th><th>Name</th><th class="danger" style="width:20%">Requirements</th><th class="success">Services</th><th>Location</th><th>Dimension</th></tr></thead><tbody></tbody></table>'); // create html tags as jQuery objects, not very long strings with data
var rowCount = 0;
for (var j = 0; j < tab.tabContent.length; j++) {
var obj = tab.tabContent[j];
// div += '<div sheet_name="' + obj.sheet_name + '">' + obj.name + '</div>';
var row = $('<tr><td></td><td></td><td class="danger" style="width:20%"></td><td class="success"></td><td></td><td></td></tr>');
rowCount++;
row.find("td").eq(0).text(rowCount);
row.find("td").eq(1).text(obj.name);
row.find("td").eq(2).text(obj.requirements ? obj.requirements[0].requirement : '');
row.find("td").eq(3).text(obj.services ? obj.services[0].service : '');
row.find("td").eq(4).text(obj.location ? obj.location : '');
row.find("td").eq(5).text(obj.dimensions ? obj.dimensions : '');
table.find("tbody").append(row);
if (obj.requirements || obj.services) {
var nMax = obj.services.length > obj.requirements.length ? obj.services.length : obj.requirements.length;
if (nMax > 1) {
var nRows = [];
for (var conut = 1; conut < nMax; conut++) {
nRows[conut] = $('<tr><td></td><td></td><td class="danger" style="width:20%"></td><td class="success"></td><td></td><td></td></tr>');
if (obj.requirements.length > conut) {
nRows[conut].find("td").eq(2).text(obj.requirements[conut].requirement);
}
if (obj.services.length > conut) {
nRows[conut].find("td").eq(3).text(obj.services[conut].service);
}
}
table.find("tbody").append(nRows);
}
}
}
div.append(table);
tabContentDiv.append(div);
}
$('.nav-tabs li').eq(0).addClass('active');
$('.tab-content div').eq(0).addClass('active');
wrapper.append(wrapperUL);
wrapper.append("<p> </p>");
wrapper.append(tabContentDiv);
return wrapper;
}

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>

How can I use jQuery to randomly select one column from each row?

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

How to read value of Textbox which is inside table

I need to read the value of textbox which is inside the table.
Following is how I create table.
var theader = '<table border = "1" id = "MarksTable">\n';
var tbody = '';
for ( var i = 0; i < total_rows; i++) {
tbody += '<tr>';
for ( var j = 0; j < total_col; j++) {
tbody += '<td name=' + "cell" + i + j + '>';
if (i > 0) {
tbody += '<input type="text" value = "marks" name="inputcell1'+j + '">';
} else {
tbody += '<b>' + subjectList[j] + '</b>';
}
tbody += '</td>';
}
tbody += '</tr>\n';
}
var tfooter = '</table>';
document.getElementById('wrapper').innerHTML = theader
+ tbody + tfooter ;
and below is my attempt to read text box value:
function readTableData(){
var marks = [];
var table = document.getElementById("MarksTable");
var column_count = table.rows[1].cells.length;
var row = table.rows[1];
if(column_count>0){
for(var index = 0; index < column_count;index++){
marks[index] = row.cells[index].innerHTML;
}
}
return marks;
}
Here, row.cells[index].innerHTML gives the output '<input type="text" value = "marks" name="inputcell10">.
Try this:
function readTableData(){
var marks = [];
var table = document.getElementById("MarksTable");
var column_count = table.rows[1].cells.length;
var row = table.rows[1];
if(column_count>0){
for(var index = 0; index < column_count;index++){
marks[index] = row.cells[index].getElementsByName('inputcell' + index)[0].value;
//Or marks[index] = document.getElementsByName('inputcell' + index)[0].value;
}
}
return marks;
}
<!DOCTYPE html>
<html>
<head>
<style>
table, td {
border: 1px solid black;
}
</style>
</head>
<body>
<p>Click the button to add a new row at the first position of the table and then add cells and content.</p>
<div id="tableContainer">
</div>
<br>
<button onclick="myFunction()">Try it</button>
<button onclick="readTableData()"> Read it </button>
<script>
function myFunction() {
var tab = '<table id="MarksTable">';
var counter = 0;
for(i = 0; i< 4; i++){
tab = tab + '<tr><td rowspan = "4"> Dept1 </td><td> <input type="text" id="inputcell'+counter+'" value="'+i+'"/> </td></tr>';
counter++;
tab = tab+'<tr><td> <input type="text" id="inputcell'+counter+'" value="'+i+'"/> </td></tr>';
counter++;
tab = tab+'<tr><td> <input type="text" id="inputcell'+counter+'" value="'+i+'"/> </td></tr>';
counter++;
tab = tab+'<tr><td> <input type="text" id="inputcell'+counter+'" value="'+i+'"/> </td></tr>';
counter++;
}
tab = tab + '</table>';
document.getElementById("tableContainer").innerHTML = tab;
}
function readTableData(){
var val;
var table = document.getElementById("MarksTable");
var column_count = table.rows[1].cells.length;
var rowcount = table.rows.length;
alert(rowcount);
if(column_count>0){
for(var index = 0; index < rowcount;index++){
var row = table.rows[index];
val = document.getElementById("inputcell"+index);
alert(val.value);
//marks = row.cells[0].getElementsByName('inputcell').value;
//Or marks[index] = document.getElementsByName('inputcell' + index)[0].value;
}
}
alert(val);
}
</script>
</body>
</html>

Categories

Resources