Generating dynamic tables using JQuery is not possible

This script is intended to generate a table and convert it into a canvas. Clicking on a cell should change its color to the selected color from the color picker input is retrieved from text boxes and the color picker, and executed upon submitting

I need to create a table with specific dimensions. However, I'm struggling to figure out how to store the values entered in the input boxes for creating the table. Additionally, I also want to save the selected color from the color picker to change the cell colors accordingly.View the page in action here.

Note: The requirement is to solve this using JQuery only.

// Select color input
// Select size input

// When size is submitted by the user, call makeGrid()
var Make=$('#pixel_canvas');
var td=$('td');

var rows=$('#input_width').val();
var cols=$('#input_height').val();
td.css("padding","700px");
function change() {
    $('td').click( function() {
        $(this).css("background-color","red");
    });
}

Make.append(makeGrid());

function makeGrid() {
    var table='';

    for (var i = 0; i < rows; i++) {
         table+='<tr>';
         for (var j = 0; j < cols; j++) {
             table+='<td onclick="change()"></td>';
         }
         table+='</tr>';
    }
    return table;
};
body {
    text-align: center;
}

h1 {
    font-family: Monoton;
    font-size: 70px;
    margin: 0.2em;
}

h2 {
    margin: 1em 0 0.25em;
}

h2:first-of-type {
    margin-top: 0.5em;
}

table,
tr,
td {
    border: 1px solid black;
}

table {
    border-collapse: collapse;
    margin: 0 auto;
}

tr {
    height: 20px;
}

td {
    width: 20px;
}

input[type=number] {
    width: 6em;
}
<!DOCTYPE html>
<html>
<head>
    <title>Pixel Art Maker!</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Monoton">
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <h1>Lab: Pixel Art Maker</h1>

    <h2>Choose Grid Size</h2>
    <form id="sizePicker">
        Grid Height:
        <input type="number" id="input_height" name="height" min="1" value="1">
        Grid Width:
        <input type="number" id="input_width" 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="pixel_canvas"></table>

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

Answer №1

When dynamically creating an HTML table, the process involves adding rows in a loop and forming a string that will be inserted into the HTML.

  • One common approach is to start the string with "<table>". Then add the desired number of rows (usually using a loop) followed by "</table>" at the end.

  • In this example, the table tag already exists in your HTML, so starting or closing the string with the table tag is not necessary. Instead, append the row description string directly to the selector $(#pixel_canvas)

To create listeners for the td tags within the table, delegation events can be used. This allows for a single listener to be added to the entire table. Rather than

table+='<td onclick="change()"></td>';
, you can achieve this with:
$('#pixel_canvas').on('click', 'td', function(e){})

let color;

// Create the Pixel Art Grid
function makeGrid() {
const table = $('#pixel_canvas');
table.find('tr').remove(); // Remove existing table if any

const size = {
height: $('#input_height').val(),
width: $('#input_width').val()
}

// Build the table
for (let i = 0; i < size.height; i++) {
let row = '<tr>';
let cell = '';
for(let j = 0; j < size.width; j++){
cell += '<td></td>';
}
row += cell;
row += '</tr>';
table.append(row);
}

}

// Call makeGrid() when user submits size
$('#sizePicker').on('submit', function(e){
e.preventDefault();
makeGrid()
})

// Change cell color
$('#pixel_canvas').on('click', 'td', function(e){
if($(e.target).css('background-color') !== color){
color = $('#colorPicker').val();
$(e.target).css('background-color', color);
color = $(e.target).css('background-color'); 
}else{
$(e.target).css('background-color', 'inherit');
}
})
body {
    text-align: center;
}

h1 {
    font-family: Monoton;
    font-size: 70px;
    margin: 0.2em;
}

h2 {
    margin: 1em 0 0.25em;
}

h2:first-of-type {
    margin-top: 0.5em;
}

table,
tr,
td {
    border: 1px solid black;
}

table {
    border-collapse: collapse;
    margin: 0 auto;
}

tr {
    height: 20px;
}

td {
    width: 20px;
}

input[type=number] {
    width: 6em;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
    <title>Pixel Art Maker!</title>
    <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Monoton">
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <h1>Lab: Pixel Art Maker</h1>

    <h2>Choose Grid Size</h2>
    <form id="sizePicker">
        Grid Height:
        <input type="number" id="input_height" name="height" min="1" value="1">
        Grid Width:
        <input type="number" id="input_width" 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="pixel_canvas"></table>

    <script src="designs.js"></script>
</body>
</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

Troubleshooting connection issues with a Chat app using Socket.io and Express: How to fix ERR

Currently, I'm immersed in a tutorial that delves into creating a rock-paper-scissors game with an integrated chat feature using socket.io and express. My focus is solely on crafting the chat component. However, a frustrating error keeps cropping up w ...

Prevent user input in HTML

Currently, I am working on creating the 8 puzzle box game using JavaScript and jQuery Mobile. The boxes have been set up with <input readonly></input> tags and placed within a 9x9 table. However, an issue arises when attempting to move a box ...

Can you modify the value of the link identified as "#showCities" based on the city that is clicked on?

There is a link called "All Country" that, when clicked, opens a modal displaying a list of cities: <a class="city" id="showCities" data-toggle="modal" data-target="#modal2" href="">All Country</a> The modal lists all the cities associated wi ...

Utilize JavaScript to establish an object with key and value pairings

Wanting to loop through and create an object that contains key => [value], if the key already exists, simply add the value. Here is what I have tried so far: let dataName = []; let obj = {}; checkboxes.forEach(checkbox => { if (checkbox.che ...

Guide to setting the radio_button checked for the first child element in Rails 4

Currently, I am working with rails4 and have encountered an issue related to a dropdown list. My goal is to automatically select the radio_button of the first child element when a parent item is chosen from the dropdown menu. Essentially, the dropdown cons ...

React 16 Component Size Attribute (size="test") is being eliminated

Is anyone else encountering a similar issue where the size attribute of a React component is getting removed? For example, `ReactDOM.render( <h1 size="hello">Hello, world!</h1>, document.getElementById("root") );` You ...

Signal processing aborted as QML QObject was destroyed prematurely

While working in QML, I'm incorporating a C++ library that produces a QObject responsible for executing a process and triggering a signal upon completion. To handle this signal in JavaScript, I utilize the connect method of the emitted signal (success ...

You are attempting to access 'https://open-api.trovo.live/openplatform/channels/id' from the source 'http://localhost:3000'

I've encountered an issue while trying to retrieve profile data from the Trovo API. Access to fetch at 'https://open-api.trovo.live/openplatform/channels/id' from origin 'http://localhost:3000' has been blocked due to CORS policy ...

Extracting JavaScript content with Selenium using Python

I am currently facing a challenge of scraping JavaScript data from a website. Specifically, I am trying to extract the number of Followers from this particular website. Here is the code I have come up with so far: import os from selenium import webdriver ...

Mastering the Art of Tallying Select Choices in Protractor

Experiencing an issue with counting options in the select attribute during my test. Here is the code snippet: it('should verify the number of options', function()) { expect(element(by.id('sorting_options')).all(by.tagName('optio ...

Transforming a PHP cURL call to node.js

Currently exploring the possibility of utilizing the Smmry API, however, it seems that they only provide PHP API connection examples. Is there anyone who could assist me in adapting it into a JS request? My requirement is simple - I just need it to analyz ...

Perfectly aligning when the width is undetermined

When centering elements with dynamic widths, I typically use the code below: .horz-vert-center { position: absolute; left: 50%; top: 50%; transform: translate(-50%, -50%); } However, a common issue I face is that the element resizes prematur ...

Transform the date time into a carbon instance

Using the date time input field with the code <input type="datetime-local"> returns a formatted date time of yyyy-MM-ddThh:mm. The goal is to convert this format to Y-m-d H:i using the php-carbon Package. An attempt was made with the following code ...

An AJAX function nested within another AJAX function

Is there a way for me to return the second ajax call as the result of the ajax function? I could use some assistance with this. function ajax(url: string, method:string, data:any = null) { var _this = this; return this.csrfWithoutDone().done(funct ...

Vuetify's offset feature seems to be malfunctioning as it does not

I'm facing an issue with the <v-flex> element in my code, specifically with the offset property not responding as expected. Despite following the recommended layout from the vuetify docs, I can't seem to get it right. Below you can see the ...

A technique to execute multiple Ajax calls simultaneously without having to wait for each one to finish in an onClick event

<html> <head></head> <body> <button onclick="ajaxcall()">Run the function</button> </body> <script> function ajaxcall() { $.ajax({ url: 'insertdata.php', ...

The userscript will keep the window open as long as it remains inactive

Hello everyone, I'm excited to join the StackOverflow community and dive into userscripts for the first time! Putting aside any unnecessary details, I'm encountering a small issue with a script I recently created. (function () { $("#enbut"). ...

Asynchronously load an AngularJS controller from AJAX without altering the route

I am looking to dynamically load an Angular controller after making an AJAX call that generates a new view in HTML. Here is the setup I currently have: Example of a View: HTML Snippet From AJAX <!-- CVS Pharmacy Extracare - Add View --> <d ...

Enclose the text within the initial cell

I am trying to encapsulate a text label in the initial column of my table within a span. Although it seems like a simple task, I am encountering some issues. Here is my attempted solution: $('#myTable tr td:first-child').each(function() { va ...

Request Denied: Ajax communication to external origin blocked

Hello everyone, I am currently attempting to send data via ajax to my API website in order to insert it into my database. However, I am encountering an error that reads: Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote re ...