Aayman Khalid
Aayman Khalid

Reputation: 468

Creating a table using JavaScript

I am new to front-end web development and right now I am working on a test task to create a table using javascript.Here is my html file:

<title>Pixel Art Maker!</title>
<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="inputHeight" name="height" min="1" value="1">
    Grid Width:
    <input type="number" id="inputWeight" name="width" min="1" value="1">
    <input type="submit" onclick="makeGrid()">
</form>

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

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

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

And my javascript file:

function makeGrid() {


var rows=inputHeight; var cols=inputWeight; //Referencw for the body var body=document.getElementsbyTagName("body")[0];

//create a table element and a <tbody> element var table1=document.createElement("table"); var tableBody=document.createElement("tbody");

//creating cells for (var i=0;i<rows;i++){  //creating a table row  var R=document.createElement("tr");     for(var j=0;j<cols;j++){        //create a table data element       var C=document.createElement("td");         R.appendchild(C);


    }   //adding the row to the end of the table body
     tableBody.appendChild(R); } //putting the <tbody> in the <table> table1.appendChild(tableBody); //appending <table> into <body> body.appendChild(table1);

}

I am supposed to get user input of rows and columns via submit button and generate a table according to that specification.So far my attmepts are unsuccessful,more precisely when I hit submit,nothing happens and the values revert back to "1".

I would really appreciate your guidance and feedback.

Upvotes: 0

Views: 5514

Answers (4)

James Long
James Long

Reputation: 4736

As @Katamari said, it looks like you're not properly accessing the elements and getting their values.

To access an element, you can use document.querySelector and pass in a CSS selector.

var rowInput = document.querySelector("#inputHeight");
var colInput = document.querySelector("#inputWidth");

Since you have assigned IDs, you could use document.getElementById

var rowInput = document.getElementById("inputHeight");
var colInput = document.getElementById("inputWidth");

Either way, you'll get an element or null if the element can't be found. Once you have the element, just get the value property to get the user results.

var rows = rowInput.value;
var cols = colInput.value;

If you want to avoid error that could be caused by not finding the element, you can check for the element before referencing the value.

var rows = 1;
var cols = 1;

if (rowInput) {
    rows = rowInput.value;
}

if (colInput) {
    cols = colInput.value;
}

This can be converted into a single line using a tenary operator

var rows = rowInput
    ? rowInput.value
    : 1;
var cols = colInput
    ? colInput.value
    : 1;

Upvotes: 0

zxbEPREF
zxbEPREF

Reputation: 202

Try this:

<form id="form-grid" method="post" onsubmit="makeGrid()">
    <h2 id="grid-size">Choose Grid Size</h2>
    <label for="inputHeight">Grid height:</label>
    <input type="number" id="inputHeight" name="height" min="1" value="1" aria-describedby="grid-size" />

    <label for="inputWeight">Grid width:</label>
    <input type="number" id="inputWeight" name="width" min="1" value="1" aria-describedby="grid-size" />

    <h2>Pick a color</h2>
    <label for="colorPicker">Color:</label>
    <input type="color" id="colorPicker" name="color" />

    <input type="submit" value="Make Grid" />
</form>

<div id="pixelCanvas"></div>

Do note the addition of explicit label's here. These are important for accessibility!

I've added a submit handler to the form, and removed it from the button. I find it's a bit cleaner, but your approach would ultimately work too.

Then in your designs.js file, you might have:

function makeGrid(event) {
    event.preventDefault(); // prevents the form from submitting

    var form = document.querySelector('#form-grid');
    var rows = form.querySelector('#inputHeight').value;
    var cols = form.querySelector('#inputWeight').value;
    var wrapper = document.querySelector('#pixelCanvas');

    var table = document.createElement('table');

    for (var r = 0; r < rows; r++) {
        var tr = table.insertRow();
        for (var c = 0; c < cols; c++) {
            var td = tr.insertCell();
        }
    }

    wrapper.appendChild(table);
}

A few reminders:

  • Use label to associate a form field with it's visible label. This is necessary for assistive technology such as screen readers.
  • Consider a fieldset to group all of the options, increasing its accessibility.

Good luck!

Upvotes: 0

Petrashka Siarhei
Petrashka Siarhei

Reputation: 732

I create function for generate body of table, and listener for butto

function createTableBody(height, width) {
    let tr = document.createElement('tr');
    let td = document.createElement('td');
    let docFr = new DocumentFragment();
    for (let i = 0; i < width; i++) {
        tr.append(td.cloneNode());
    }
    for (let i = 0; i < height; i++) {
        docFr.append(tr.cloneNode(true));
    }
    return docFr;

}
let table = document.getElementById('pixelCanvas');
let createTableButton = document.getElementById('createTableButton');
let inputHeight = document.getElementById('inputHeight');

let inputWidth = document.getElementById('inputWeight');
createTableButton.addEventListener('click', () => {
    let parentTable = table.parentNode;
    let tableClone = table.cloneNode();
    parentTable.replaceChild(tableClone, table);//clear old table
    table = tableClone; 
    tableClone.append(createTableBody(inputHeight.value, inputWidth.value));
    // if you need , you can add ajax request 
    console.log(table)
});
<title>Pixel Art Maker!</title>
<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>
    Grid Height:
    <input type="number" id="inputHeight" name="height" min="1" value="1">
    Grid Width:
    <input type="number" id="inputWeight" name="width" min="1" value="1">
    <input type="button"  id="createTableButton">
<h2>Pick A Color</h2>
<input type="color" id="colorPicker">

<h2>Design Canvas</h2>
<table id="pixelCanvas"></table>
 </body> </html>
If you need send data to server, you can use ajax, and i replace your submit to button, remove form.

Upvotes: 0

Roko C. Buljan
Roko C. Buljan

Reputation: 206669

  1. You don't need a <form>. There's nothing to submit to.
  2. Use document.getElementById
  3. You already have a <table id> in HTML. Reference it!
  4. You don't need therefore a document.body reference.
  5. To retrieve the integer use parseInt( number, radix ) since input value is a String
  6. Clear your table from existing content before appending new stuff.
  7. Use addEventListener(EventName, callback) instead of inline JavaScript (onclick)
  8. Weight is not Width!

function makeGrid() {

  var ELTable       = document.getElementById("pixelCanvas"); // You already have it!
  var ELInputHeight = document.getElementById("inputHeight");
  var ELInputWidth  = document.getElementById("inputWidth");
  var rows = parseInt(ELInputHeight.value, 10);
  var cols = parseInt(ELInputWidth.value, 10);  // Weight? you mean Width!

  ELTable.innerHTML = ""; // Empty table before inserting new stuff

  var tbody = document.createElement("tbody");
  
  for (var i = 0; i < rows; i++) {           // N rows...
    var R = document.createElement("tr");    // Make row.
    for (var j = 0; j < cols; j++) {         // N cells...
      var C = document.createElement("td");  // Make cell.
      R.appendChild(C);                      // Insert cell into row.
    }
    tbody.appendChild(R);                    // Insert row into tbody
  }
  
  ELTable.appendChild(tbody);                // Insert tbody into table
}

document.getElementById("makeGrid").addEventListener("click", makeGrid);
td { padding:10px; background:#000; }
Height: <input type="number" id="inputHeight" min="1" value="1"> 
Width: <input type="number" id="inputWidth" min="1" value="1">
<button id="makeGrid">MAKE</button>
<br>
Color: <input type="color" id="colorPicker">
<table id="pixelCanvas"></table>

Upvotes: 1

Related Questions