Tips for assigning a random numerical value to each cell

I am struggling to assign each cell a random double-digit number between 50 and 500. I have been attempting to use the Math.floor(Math.random()) function but have not had any success so far.

Additionally, I am trying to figure out how to target only one cell. For example, if I have a grid of 5x5 slots with 5 rows and 5 columns, how can I isolate the top left cell? Instead of a randomly generated number like the rest of the cells, I want to give it a specific symbol that I can control. That way, if the symbol is in the top left corner and I click on another cell, I can move the symbol there, replacing the generated number and leaving the top left corner empty.

I apologize for the inconvenience, any assistance would be greatly appreciated.

<html>
<head>
<style>
td{
border:2px solid black;
width:10px;
height:10px;
}
td:hover{background-color:lightgreen;}
.grn{
background-color:green;
color:white;
}
</style>

<body>
<div id='ff'></div>

<script>
var isCol=0;
var board=[];
for(r=0;r<7;r++){
    var line=[];
    for(c=0;c<7;c++){
        line.push(r);
    }
    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;
}


showTable(-1);
</script>
</body>
</html>


Answer №1

Give this a shot.

function generateRandomRange(min, max) {
  return Math.floor(Math.random() * (max - min) + min);
}

const num_rows = 7;
const num_cols = 7;

const matrix = Array.from(new Array(num_rows), () =>
  new Array(num_cols).fill(0).map(() => generateRandomRange(50, 500))
);

console.log(matrix);

Answer №2

It has come to my attention that you are utilizing isCol as a toggle each time a cell is clicked. Rather than using addition and modulus, consider using a boolean variable.

let isCol = false;

function prs(...) {
    showTable(...);
    isCol = !isCol;
}

This approach will simplify your toColor statement.

if (isCol) {
    return row === chosen_row;
} else {
    return col === chosen_col;
}

Answer №3

Aside from seeking help on Stack Overflow for generating random numbers within a range...
It seems like you may be overcomplicating the code. Here's an alternative approach:

const size = 5;
const rand = (min, max) => ~~(Math.random() * (max - min) + min);
let tdEmpty = null;            

const moveValue = evt => {
  const text = evt.target.textContent;
  if (!text) return;
  tdEmpty.textContent = text;  
  evt.target.textContent = ''; 
  tdEmpty = evt.target;        
};

const newTD = TR => {
  const td = TR.insertCell();
  const text = tdEmpty ? rand(50, 501) : ""; 
  td.appendChild(document.createTextNode(text));
  td.addEventListener('click', moveValue); 
  if (!tdEmpty) tdEmpty = td;             
};

const newTR = TABLE => {
  const tr = TABLE.insertRow();
  for (let i=0; i<size; i++) newTD(tr);
};

const table = document.createElement('table');
for (let i=0; i<size; i++) newTR(table);

document.querySelector('#ff').appendChild(table);
td { border: 2px solid black; }
td:hover { background-color: lightgreen; }
<div id='ff'></div>

Related resources:

Inserting Rows in HTML Tables
Inserting Cells in HTML Tables
Creating Text Nodes in HTML Documents
How to Generate Random Numbers in a Specific Range using JavaScript?

Answer №4

Hopefully, my understanding is precise.

Ensure to consider

Math.floor(Math.random() * (MAX - MIN + 1)) + MIN
, do not overlook the significance of "+ 1". Without this addition, attaining 500 will remain unachievable (499 acts as the maximum value, a fact I aim to highlight in my comments).

Moreover, rather than establishing a single callback for each cell, it would be more efficient to create a unified callback for the "click" event on the table. Subsequently, you can determine the element where the event occurred. I encourage you to delve into information regarding Event Bubbling and Propagation in JavaScript. It perfectly aligns with your current objective.

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Table</title>
    <style>
        td{
            border:2px solid black;
            width:10px;
            height:10px;
        }

        td:hover{
            background-color:lightgreen;
        }

        .grn {
            background-color:green;
            color:white;
        }
    </style>
</head>
<body>
    <div id="ff"></div>
    <script>
        'use strict';

        const SIZE = 10;        // Size of the table (SIZE x SIZE)
        const MIN = 50;         // Minimal number in cell
        const MAX = 500;        // Maximum number in cell
        const CHOSEN_COL = 0;   // Column where chosen cell is
        const CHOSEN_ROW = 0;   // Row where chosen cell is
        const SYMBOL = 'S';     // Yours 'symbol'

        function showTable() {
            let table = document.createElement('table');
            let chosenTd;   // <td> element of chosen cell

            for (let i = 0; i < SIZE; i++) {
                let tr = document.createElement('tr');
                for (let j = 0; j < SIZE; j++) {
                    let td = document.createElement('td');

                    // 1) Math.random() returns values from 0 (inclusive) to 1 (exclusive)
                    // 2) Math.random() * (MAX - MIN) returns values from 0 (inclusive)
                    // to (MAX - MIN) (exclusive)
                    // 3) Math.random() * (MAX - MIN + 1) returns values from 0 (inclusive)
                    // to (MAX - MIN + 1) (exclusive)
                    // 4) Math.floor(Math.random() * (MAX - MIN + 1)) returns values from 0 (inclusive)
                    // to (MAX - MIN) (inclusive!!!)
                    // 5) Math.floor(Math.random() * (MAX - MIN + 1)) + MIN returns values from
                    // MIN (inclusive) to MAX (inclusive) - exectly what we need
                    //
                    // Pay attention to 'inclusive' and 'exclusive'
                    td.textContent = Math.floor(Math.random() * (MAX - MIN + 1)) + MIN;

                    // Obvious (I hope)
                    if (i == CHOSEN_ROW && j == CHOSEN_COL) {
                        chosenTd = td;
                        chosenTd.className = 'grn';
                        chosenTd.textContent = SYMBOL;
                    }

                    tr.append(td);
                }
                table.append(tr);
            }

            table.onclick = function(e) {
                // If we click not at chosen cell (you call it 'symbol')
                if (e.target != chosenTd) {
                    // Now just free cell where 'symbol' is
                    // And 'move' the 'symbol'

                    e.target.textContent = chosenTd.textContent;

                    chosenTd.className = '';
                    chosenTd.textContent = '';

                    chosenTd = e.target;
                    chosenTd.className = 'grn';
                }
            }

            document.querySelector('#ff').append(table);
        }
    </script>
</body>
</html>

In addition, remember to validate that e.target specifically refers to a cell, rather than a row or the entire table, for instance. Nevertheless, I believe you possess the capability to accomplish this task autonomously.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The incompatible peer dependency of node.js is causing issues with running npm update

C:\Users\Projects\webapp +-- UNMET PEER DEPENDENCY <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6012050103142051554e544e52">[email protected]</a> `-- UNMET PEER DEPENDENCY <a href="/cdn-cgi/l/e ...

How to reset the value in a select box using jQuery

Looking at my code, I have some markup and jQuery javascript set up like this: let color_select = $('select#SelectByColor'); color_select.val([]); <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></sc ...

What is the best way to enable a CSS table column to overflow the table while having a width of 100%?

I am faced with a CSS table dilemma where I have two columns, but one of them is hidden by setting its width to 0. The second column takes up the entire table by being set to a width of 100%. However, when the first column is shown (controlled by a checkbo ...

Searching for and replacing text that spans across multiple nodes in HTML can be accomplished using C# programming language

Here is the HTML code to consider. The term 'response' was modified to 'reason', by removing 'sp' (<del> tag) and adding 'as' (<ins> tag), while also removing 'se' (<del> tag). <div &g ...

When setting an empty URL with Fabricjs' setBackgroundImage function, a null reference error occurs in the _setWidthHeight

Recently, I stumbled upon an article detailing a method to clear the background of a fabric canvas... canvas.setBackgroundImage('', canvas.renderAll.bind(canvas)); In the development of my online design tool which utilizes Fabricjs 1.4.4, I have ...

Troubleshooting problem with Bootstrap column and grid dimensions

I have a Bootstrap page displaying a title along with 2 forms in a single row positioned above a table. The 2nd form, located at the top left above the table, is currently occupying the full width of the parent column (col-md-8) when it only needs to occup ...

Is there a method to divide a table's TD into two interactive segments?

I'm attempting to create a TD element that can accommodate two entries with a line separating them. This is what the TD will look like on the webpage (1 TD with 2 distinct sections): val/tot ___ ___ | 6 | 5 | --- --- Thank you! ...

Utilizing Ajax to send a parameter to a separate PHP script

I have a dilemma that I need help with. Currently, I have a table displaying data using PHP and SQL in the following format: What I want to achieve is to be able to click a button, retrieve the ID value, and based on that, execute another SQL query to dis ...

Exploring Ember Octane (version 3.22 and above): benefits of using {{on 'click' this.function}} over traditional onclick={{this.function}} method

When working with Ember Octane, there are two different ways to attach a function to an event in an hbs file. The first way is the EmberJS approach: {{on 'click' this.function}} Alternatively, you can use the classic HTML method: onclick={{this ...

The height of the webpage is extended when viewed on mobile Safari

After creating a website that functions smoothly on all platforms, I encountered a problem with mobile Safari. On this browser, the page height is inexplicably stretched and the page becomes unresponsive after the first click. html,body { height:100%; ...

Show label and selection box

I've been trying to add a checkbox to the display tag table, but I'm having trouble getting it to function properly. I want the header checkbox to select all rows in the table when checked Additionally, individual rows should be selectable Whe ...

Creating a web form with HTML and integrating it with jQuery AJAX

Looking to fetch data from the server through jQuery AJAX on an HTML form and store the response in a PHP string variable. Here is my current code snippet: <form method="post" name="myform" id="myform" action="https://domain.com/cgi-bin/cgi.exe"> &l ...

Node.js throws an error when accessing req.body as undefined

My task involved creating a basic API using node.js and express, with the addition of body-parser. However, I encountered an issue where req.body was returning undefined. Here is a snippet of my app.js: const express = require('express'); const b ...

react: implement custom context menu on videojs

Can someone assist me with adding a quality selector and disabling the right-click option in a webpage that uses videojs? I am unsure about using plugins, as there were no examples provided in react. Any guidance would be appreciated. VideoPlayer.js impor ...

Show information from a MySql table starting with the most recent entries and ending with

I'm looking to present data from a MySQL table in an HTML table. I want the newest posts to appear at the top, descending down to the oldest post. However, my current code arrangement displays the most recent data added from my form at the bottom of ...

Encountering an error while trying to import GraphQL resolvers and schema

Upon attempting to start the server with the following setup, an error is encountered: Error: "createUser" defined in resolvers, but has an invalid value "function (userInput) {... The resolver's value must be of type object. index.ts const schema ...

Exploring MongoDB - when we need to peel back nested subdocuments

Consider the following dataset: lists { _id: 1, included_lists: [ 2 ], items: [ "i1" ]} { _id: 2, included_lists: [], items: [ "i2", "i3" ]} items { _id: "i1", details: [{}, {}, {}]} { _id: "i2", details: [{}, {}, {}]} { _id: "i3", details: [{}, {}, {} ...

Continuous front-end promise awaiting response from back-end Node.js function

Currently, I am working on a basic React frontend where I need to fetch some data from my backend API powered by Node.js. This backend API calls an external API to get the required data. Although I have verified that the data is fetched successfully on the ...

Discover the following item using jQuery

Here is some HTML code that I have: <div class="form-group"> <input type="text" class="sequence valid"> </div> <div class="form-group"> <input type="text" class="sequence valid"> </div> <div class="som ...

Troubleshooting Angular and Ionic: Unable to Retrieve Value from HTML Input Element

Check out the HTML code below: <div class="list"> <label class="item item-input"> <input id="email" ng-model="email" type="text" placeholder="Email Address"> </label> < ...