JavaScript allows you to create matrices from squares

Hey everyone,

I'm facing an issue with creating matrices in HTML. I need to display a 5x5 matrix where each index is represented by a square. I tried using a span template for the box and then wrote a script to populate the matrices, but it's not working as expected. Here's what I'm getting:


[object HTMLSpanElement][object HTMLSpanElement][object HTMLSpanElement][object HTMLSpanElement][object HTMLSpanElement]
[object HTMLSpanElement][object HTMLSpanElement][object HTMLSpanElement][object HTMLSpanElement][object HTMLSpanElement]
[object HTMLSpanElement][object HTMLSpanElement][object HTMLSpanElement][object HTMLSpanElement][object HTMLSpanElement]
[object HTMLSpanElement][object HTMLSpanElement][object HTMLSpanElement][object HTMLSpanElement][object HTMLSpanElement]
[object HTMLSpanElement][object HTMLSpanElement][object HTMLSpanElement][object HTMLSpanElement][object HTMLSpanElement]

Here is the code snippet:


    <style>
        html {
            background-color: #E6E6FF;
        }
        #square{
            width: 30px;
            height: 30px;
            background: #000;
            display: inline-block;
            border: 1px solid #fff;
        }
    </style>

<head>
<body>
<div id="matrixBox">
    <span id="square"></span>
</div>

    <script>

    var x = 5;
    var y = 5;
    var matrix = [];
    var content= '';
    var matrixBox = document.getElementById("matrixBox");
    var square = document.getElementById("square");

    for (var i = 0; i < x; i++) {
        matrix[i] = [];
        for (var s = 0; s < y; s++) {
            matrix[i][s] = square;
            content += matrix[i][s];
            document.getElementById("matrixBox").innerHTML = content;
        };
        content += "<br>";
    };
    </script>
</body>

Thank you for the help!

Answer №1

Take a look at the code snippet below. In this case, the "Matrix" serves as the array which can be utilized for computations.

<html>
  <style>
        html {
            background-color: #E6E6FF;
        }
        #square{
            width: 30px;
            height: 30px;
            background: #000;
            display: inline-block;
            border: 1px solid #fff;
color:#fff;
text-align: center;
vertical-align: abs-middle;
top: 50%;
left: 50%;
        }
    </style>
 
</head>
<body>
<div id="matrixBox">
   
</div>

   
</body>
<script language="javascript">

    var x = 5;
    var y = 5;
    var str='';
var matrix=new Array();


    for (var i = 0; i < x; i++) {
matrix[i]=new Array();
        for (var s = 0; s < y; s++) {
matrix[i][s]=i;
            str+=" <span id=square> "+ i + " </span>  ";
         };
        str += "<br>";
    };

 document.getElementById("matrixBox").innerHTML = str;
 alert(matrix);
    </script>
</html>

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

CSS border margin-bottom attribute not functioning correctly

I am trying to create a page border by wrapping it around the content using a <div> element. The parent element is the actual page itself. However, I'm having trouble with the margin-bottom property as it doesn't seem to be working properly ...

How can JavaScript be used to activate HTML5 AppCache?

<html manifest="example.appcache"> Is it possible to use javascript to include the manifest="example.appcache" part? ...

Avoiding the overlap of sub-menu items vertically

My nested unordered list acting as a sub-menu has an issue with overlapping list items. It seems like the padding of the links is causing the overlap: ul { padding: 12px 0; list-style: outside none none; } li { display: inline-block; margin-righ ...

Utilizing array.filter() to retrieve objects with values containing specified keywords

In my node.js project, I have an array named products that is structured as follows: [ { product_id: 'adidas-training-shoes', title: 'Adidas Training Shoes', description: 'description', brand: 'brand&a ...

Yeoman Error: Issue with 'mkdir' in Javascript Execution

Currently, I am in the process of setting up a Meanjs instance using a Yeoman generator. However, when I execute 'sudo yo meanjs', everything goes smoothly until an issue arises while attempting to create a directory and it fails. Any insights on ...

When adding a new div, ensure it is counted and delete it once a new div is added

When clicked, a new div is added. When clicked again, another div with the same content is created as a duplicate. Q: Is there a way to remove the previous div when a new one is created? $(document).on('click', '.LibSectOpen', functio ...

CORS blocked the JavaScript Image's request

I am encountering an issue with my code that involves capturing selected divs using the HTML2Canvas library. However, when I try to download the captured image file, it is not working as expected. The error message I keep receiving is "Access to Image at ...

How can I integrate material-ui with react-jsonschema-form?

Currently, I am working on a form utilizing react-jsonschema-form. However, I would like to further enhance the appearance of my application (including the form) by incorporating Material-UI. I am encountering difficulties integrating both frameworks toget ...

Using Node.js to write data to a JSON file

Currently, I am working on a program that scans through an array containing numerous links. It reads through each link, extracts specific text, and then stores it in an output file as JSON. However, I am facing an issue with formatting the JSON file. The ...

Validating the existence of a URL using jQuery and AJAX

I'm currently facing a puzzling situation. I'm attempting to iterate through a list of Youtube ids to verify if the videos still exist. I've stored all the ids in an array and I'm utilizing the gdata API to determine if I receive XML r ...

Why is it not possible to establish a minimum height of 100% in html?

HTML Code: <!DOCTYPE html> <html> <head></head> <body> <link rel="stylesheet" type="text/css" href="style.css"> <div class="sheet" style="width:80%;max-width:1024px;height:400px;"></div> ...

I'm having trouble getting my Ajax edit code to function correctly. Can anyone offer some assistance?

I am currently working on a basic registration system that includes two forms: one for registration and another for selecting a city. I have encountered an issue where newly added cities update perfectly, but when trying to use the selected city in the reg ...

Can you help me adjust the height of my banner and center its content vertically?

Looking to create a custom banner for my website, specifically at the top with dimensions of 700px width and 80px height. The code snippet is as follows: <div class="container-narrow" style="heigth: 80px;"> <img src="#" width="52" ...

Would it be feasible to rename files uploaded to Firebase within an AngularJS controller using logic?

Is there a way to apply regex to rename uploaded files before saving them to firebase storage? It seems that firebase file metadata does not support this function. I am currently using angularjs and would appreciate any guidance on this matter. ...

Tips for toggling password visibility by clicking outside a password field

As I work on creating a password field that allows users to toggle the visibility of their password by clicking an eye icon, I am facing a challenge. I want the password to be hidden automatically when the user clicks outside the field, which requires a co ...

What is the best way to create a JQuery click event that applies to every button on my webpage?

I am working on a website settings page where logged-in users can edit the content displayed on the public page. I have a form that uses AJAX to update the content when submitted. My main question is how to modify the code so it can determine which text b ...

What methods are available for testing JavaScript interactions like freehand drawing on an HTML5 canvas using a mouse?

When it comes to testing object states, I am well-versed in using rspec in Ruby on Rails models. For instance, ensuring that a certain object meets certain expectations based on its prior state and a specific call. However, I am now faced with a new chall ...

Execute index.js code from index.html using NodeJS and Express

Currently, I am diving into the world of NodeJS and Express using Replit.com for a small project. The main objective is to develop a basic input field that, upon submission, will post to different channels such as Discord and Twitter. The piece of code be ...

Which file extension is superior for SEO: .html, .php, or .aspx?

Which file extension is more SEO-friendly: .html, .php, or .aspx? Or is an extension-less URL the best option for SEO? ...

Trouble with the datepicker

I tried using the datepicker from and followed its demo, but unfortunately, the datepicker is not showing up on my page. I have gone through everything carefully, but I am unable to identify the reason behind this issue. Could someone please assist me i ...