A guide on traversing a HTML table and cycling through its contents with JavaScript

I'm currently in the process of constructing a grid with 20 rows and 20 columns of squares, but I am encountering difficulties with looping through table values to effectively create the grid.

For more detailed information on the html code, please see below:

Please refer to the comments for visuals on the setup.


    <body>
        <h1>Pixel Art Maker</h1>

    <h2>Choose Grid Size</h2>
        <form id="sizePicker">
            Grid Height:  
            <input type="number" id="inputHeight" name="height" min="1" value="1"> 
            Grid Width: 
            <input type="number" id="inputWidth" name="width" min="1" value="1">
            <input type="submit">
        </form>

    <h2>Pick A Color</h2>
        <input type="color" id="colorPicker">

    <h2>Design Canvas</h2>
    <table id="pixelCanvas"> <tr> <td>  </td>  </tr> </table>

    <script src="designs.js"></script>
    </body>

    table,
    tr,
    td {
        border: 1px solid black;
    }
    tr {
        height: 20px; //some how this is working as it's the same as 
                      //td when i edit it the td gets edited aswell
        width: 20px;
    }

    td {
        height: 20px; //same as here
        width: 20px;
    }

    const lTable = document.querySelector("pixelCanvas"); 
    
    let height = document.querySelector("#inputHeight");
    
    let width = document.querySelector("#inputWidth");
    

    function makeGrid() {

    //This is the main problem i can't figure out how to iterate the value
    // to make the actual grid and give it the event listener

}

Answer №1

There is no need for a form unless you plan on submitting data to an API.

Discover a simple solution for your issue below:

    
    
    function createGrid() {
      let height = document.querySelector("#inputHeight").value;
      //Storing the value of the inputHeight element
      let width = document.querySelector("#inputWidth").value;
      //Storing the value of the inputWidth element
      //Selecting my table and storing it in a variable
      const gridTable = document.querySelector("#pixelCanvas"); 
      //The challenge here is figuring out how to iterate the value
      // to create the actual grid and add the event listener
      for (var i=0; i< height;i++) {
        var row = gridTable.insertRow(i);
        for (var j=0; j< width;j++) {
          row.insertCell(j);
        }
      }
    }
table {
  border: 1px solid black;
}
table td {
  border: 1px solid black;
  height: 20px; 
  width: 20px;
}
<div>
  <label for="inputHeight">Height</label>
  <input type="text" id="inputHeight" value="0"/>
</div>
<div>
  <label for="inputWidth">Width</label>
  <input type="text" id="inputWidth" value="0"/>
</div>
<input type="submit" value="Draw" onClick="createGrid()"></input>
<table id="pixelCanvas"></table>

Answer №2

Check out this helpful fiddle:

https://jsfiddle.net/qh6zjfmw/

This function creates a grid where each cell contains data-row and data-col attributes to identify the clicked element. Additionally, each cell has classes .row-number and .col-number for targeting specific elements to toggle the class (active/inactive)

    displayGrid(13, 13);

    function displayGrid(rows, cols){
        for (var r = 0; r < rows; r++){
        console.log(r+1);
        $('<div class="row row-'+r+'"></div>').appendTo(".grid");

          for (var c = 0; c < cols; c++){
            console.log(c+1);
            $('<div class="col col-'+c+'" style="width:'+100/cols+'%; padding-bottom:'+100/cols+'%" data-row="'+r+'"  data-col="'+c+'"></div>').appendTo(".grid .row-"+r);

          }

        }
    }

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 page only appears properly after clearing the cache

My floating list menu is behaving oddly in Firefox. It only displays correctly after clearing the cache, but as soon as I refresh the page, the menu breaks again. The links inside the list elements appear wider than the text, even though I haven't se ...

Issues encountered while trying to integrate chessboard.js into a Vue application

I am facing an issue while trying to incorporate chessboard.js into my jetstream-vue application. Following the creation of the project, I executed the command npm install @chrisoakman/chessboardjs which successfully downloaded the package into my node_mod ...

Modify the CSS properties of the asp:AutoCompleteExtender using JavaScript

Is there a way to dynamically change the CompletionListItemCssClass attribute of an asp:AutoCompleteExtender using JavaScript every time the index of a combobox is changed? Here is the code snippet: ajaxtoolkit: <asp:AutoCompleteExtender ID="autocom" C ...

Troublesome CSS conflicts arise when using minified assets with AngularJS and Webpack

After transitioning my Angular project to the Webpack build system, I encountered issues with Angular Dependency Injection in the JS source code. Surprisingly, now I am facing JS errors that are targeting CSS files, leaving me completely bewildered about w ...

Map image showing only the tile layer in the top corner

My current project involves utilizing Ionic 5 and Vue.js. One of the screens in my project features a leaflet map that needs to cover most of the screen space. To implement this, I have integrated the Leaflet library for vue into my code. Here is a snippe ...

A guide on implementing a TypoError in Node.Js and Discord.Js for enabling a bot to enter a voice channel

Hello there, I'm currently working on a music Bot for Discord using Javascript with Node.Js and I've encountered an issue: This problem arises specifically with the "play" command, but it seems to occur with all commands that involve joining a v ...

What could be the reason for StaticComponent constantly re-rendering despite having a static state that does not change

I'm trying to grasp the core concepts of how React triggers component re-rendering upon state changes. In the scenario described below, the console.log('hi') statement within the StaticComponent is executed every time the onChange event han ...

Is it necessary to incorporate express in a Next.js project?

I'm currently working on a website using Next.js. With Next.js, I have access to features like SSR and dynamic routing. Is it necessary for me to incorporate express into my project? If yes, what are the reasons behind needing to use it? What unique ...

Challenges with the Placement of Buttons

I am facing an issue with the code below: document.addEventListener("DOMContentLoaded", function(event) { // Select all the read more buttons and hidden contents const readMoreButtons = document.querySelectorAll(".read-more"); const hiddenConten ...

There is a lack of 'Access-Control-Allow-Origin' header - Issue encountered while making Food2Fork API request using AJAX

Our team has just embarked on our first project, and I've encountered a roadblock while conducting API testing. Specifically, I am struggling to generate a successful access control header. Is there anyone who can provide assistance in troubleshooting ...

Merge identical year items into a single entity

I have an array of objects containing car data: [ { year: 2019, company: 'Toyota', quantity: '450' }, { year: 2019, company: 'Ford', quantity: '600' }, { year: 2020, company: ...

Ensure that the token remains current with each axios operation

I need to access an Express REST API that demands a valid json web token for certain routes. In order to include the token from localstorage every time I needed, I had to create an "Axios config file". My http.js file includes the code below: import Vue ...

The BeautifulSoup parsing result differs from the code of the original HTML page

Lately, I've been using BeautifulSoup4 to scrape data from Spotify Charts. It's been working smoothly for a few weeks until today when it suddenly started giving NaN values for all the entries... I suspect that the issue lies in the parsed HTML ...

When using React and React Router v6, make sure to implement a 404 status code response for unmatched routes

When it comes to managing unmatched routes with React Router, I have a solid understanding: <Routes> {/* Public routes */} <Route exact path="/" element={<Home />} /> // Other routes... {/* Error routes */} ...

Oops! The API request was denied with error code 401 - Unauthorized in React

I have been working on incorporating an API into my front-end project using React/Typescript. The documentation for the API specifies that authorization requires a key named token with a corresponding value, which should be included in the header. To stor ...

How about designing a button with a dual-layered border for a unique touch

Looking for a specific button: My attempted CSS code that's not working: button { font-family: 'Ubuntu', sans-serif; font-size: 1em; font-weight: bold; color: white; border: 3px double #f26700; background: #f26700; ...

Is there a way to customize the color of the collapsible menu?

I am currently delving into Bootstrap to enhance my skills. I decided to utilize the example navbar provided in the documentation: <nav class="navbar navbar-expand-lg navbar-light bg-primary"> <div class="container-fluid"&g ...

Is it possible to utilize the import feature to access and read a JSON file within a Next.js 13 API scenario?

Currently, in my Next.js 13 project, I am using the App Router feature to work with an API route that reads a file from a language folder within the resources directory. The code structure of this API is as follows: // app/api/file/[lang]/write/route.ts i ...

Is there a way to transfer a variable from Angular 2 Frontend Express JS to an Angular 2 component?

After conducting thorough research, I have made specific modifications to my code. However, I am encountering some errors in my console that I cannot seem to resolve. Despite following a tutorial step by step. Your assistance would be highly valued as I a ...

Drawing recursive 2D tree fractals using WebGL technology

Attempting to create a binary fractal tree in webgl, but struggling with the branch angles not aligning as desired. The approach involves plotting vertex points into an array, converting it into a float32array, and then utilizing drawArrays(LINE_STRIPE) fo ...