Establishing a Table of Disarray

I've hit a roadblock and I'm feeling confused about where to go next.

Currently, I'm exploring the use of JavaScript to create tables for my data and display them in HTML. While I've successfully created the HTML table, I'm facing some challenges with the JS table.

Here's an illustration of what I'm aiming for:

Now, here's the code snippet I have for drawing the table. However, I'm stuck at the 7th row and unsure how to proceed further.

Despite reading numerous resources, I still can't seem to crack it!

This is the code I've written so far:

function drawTable3() {
  var input = document.createElement("input");
  var tr = document.createElement("tr");
  var td = document.createElement("td");

  var div = document.getElementById("dropper")

  //create table
  var drawTable = document.createElement("table");
  drawTable.id = "dropperTable";
  drawTable.className = "tg";
  div.appendChild(drawTable);

  var table = document.getElementById("dropperTable");

  var input = document.createElement("input");
  input.id = "D" + [i] + "Size";
  input.type = "number";


  //Create Head Elements
  for ( var i = 0; i < 3; i++ ) {
    var createHead = document.createElement("th");
    if ( i == 0) {
      createHead.innerHTML = "";
    } else if ( i == 1) {
      createHead.innerHTML = "Dropper Duct Size";
    } else if ( i == 2) {
      createHead.innerHTML = "Dropper Duct Capacity";
    }
    table.appendChild(createHead);
  }

  for ( var i = 1; i < 7 ; i++ ) {

    var rowCount = table.rows.length;
    var row = table.insertRow(rowCount);

    var cell1 = row.insertCell(0);
    var dropperName = document.createElement("output");
    dropperName.id = "D" + [i] + "Size";
    dropperName.innerHTML = "Dropper Duct Side " + [i];
    cell1.appendChild(dropperName);

    var cell2 = row.insertCell(1);
    var dropperInput = document.createElement("input");
    dropperInput.type = "number";
    dropperInput.id = "D" + [i] + "Capacity";
    cell2.appendChild(dropperInput);

    var cell3 = row.insertCell(2);
    var dropperOutput = document.createElement("output");
    dropperOutput.id = "D" + [i] + "Capacity";
    cell3.appendChild(dropperOutput);

  }

}

drawTable3();
.tg  {
border-collapse:collapse;
border-spacing:0;
text-align: center;
}

.tg td{
font-family:Arial, sans-serif;
font-size:14px;
font-weight:normal;
padding:10px 5px;
border-style:solid;
border-width:1px;
overflow:hidden;
word-break:normal;
text-align: center;
}

.tg th{
font-family:Arial, sans-serif;
font-size:14px;
font-weight:normal;
padding:10px 5px;
border-style:solid;
border-width:1px;
overflow:hidden;
word-break:normal;
text-align: center;
vertical-align: top;
}
.tg .tg-s6z2{
text-align:center
}

.smallInput {
width: 50px;
text-align: center;
}
.roomIdent {

}

.factors {
text-align: center;
width: 80px;
}

.factors2 {
text-align: center;
width: 150px;
}
.tg2 {
border-top-style: none;
border-right-style: none;
border-bottom-style: none;
border-left-style: none;
border-top-color: #FFF;
border-right-color: #FFF;
border-bottom-color: #FFF;
border-left-color: #FFF;
}
<div id="dropper"></div>

Answer №1

Here are some thoughts on your code:

function createTable() {
  var inputField = document.createElement("input");
  var trElement = document.createElement("tr");
  var tdElement = document.createElement("td");

The variables trElement and tdElement are not utilized anywhere, while inputField is re-initialized later in the code.

  var tableContainer = document.getElementById("dropperBox")

  //create table
  var newTable = document.createElement("table");
  newTable.id = "dropperTable";
  newTable.className = "tg";
  tableContainer.appendChild(newTable);

  var mainTable = document.getElementById("dropperTable");  

Since you already have a reference to the table as newTable, consider using that variable name from the beginning instead of changing it later. The following lines achieve the same result:

  var mainTable = newTable;

.

  var newInput = document.createElement("input");

You previously created an input element and stored it in inputField, however, this creates a new input field replacing the previous one.

  newInput.id = "D" + [i] + "Size";

At this point, the variable i has not been assigned any value yet, so its value is undefined. Consequently, the ID assigned is:

'DSize'

. newInput.type = "number";

  //Create Table Headers
  for (var i = 0; i < 3; i++) {
    var headerCell = document.createElement("th");
    if (i === 0) {
      headerCell.innerHTML = "";
    } else if (i === 1) {
      headerCell.innerHTML = "Dropper Duct Size";
    } else if (i === 2) {
      headerCell.innerHTML = "Dropper Duct Capacity";
    }
    mainTable.appendChild(headerCell);
  }

You can make the above code more concise by utilizing an array for the values and setting them based on the value of i. Additionally, inserting a text node might be a better option for simply setting a text value:

  var headerValues = ['','Dropper Duct Size','Dropper Duct Capacity'];    
  for (var i = 0; i < 3; i++) {
    var headerCell = document.createElement("th");
    headerCell.appendChild(document.createTextNode(headerValues[i]));
    mainTable.appendChild(headerCell);
  }

.

  for (var i = 1; i < 7 ; i++) {

    var rowCount = mainTable.rows.length;
    var newRow = mainTable.insertRow(-1);

It appears that the variable rowCount is only referenced here. To append a row using insertRow, provide a value of -1:

    var newRow = mainTable.insertRow(-1);

.

    var cell1 = newRow.insertCell(0);
    var dropperName = document.createElement("output");
    dropperName.id = "D" + i + "Size";

Similarly, use i directly to get something like "D0Size":

    dropperName.id = "D" + i + "Size";

.

    dropperName.innerHTML = "Dropper Duct Side " + i;

Apply the same approach throughout the rest of your code. Consider cloning entire rows for efficiency rather than creating individual elements one by one, or designing separate functions for different types of rows. It seems like the header and footer sections could potentially be static HTML, with only the middle rows needing dynamic creation.

    cell1.appendChild(dropperName);     

    var cell2 = newRow.insertCell(1);
    var dropperInputField = document.createElement("input");
    dropperInputField.type = "number";
    dropperInputField.id = "D" + i + "Capacity";
    cell2.appendChild(dropperInputField);

    var cell3 = newRow.insertCell(2);
    var dropperOutputField = document.createElement("output");
    dropperOutputField.id = "D" + i + "Capacity";
    cell3.appendChild(dropperOutputField);   
  }
}

createTable();

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

Having trouble appending the integer to the xpath which is causing it not to be located

for x in range(1, 6): col = driver.find_elements_by_tag_name("td") for y in range(1, 7): xpath_string = '/html/body/div[3]/ul/li[1]/div/div[1]/table/tbody/tr[{0}]/td[{1}]'.format(str(y), str(x)) day = driver.find_element_by_xpath( ...

Tips for displaying a placeholder image within the Next.js image component

I am currently facing an issue with displaying images from API calls. To handle situations where there are no images or errors, I have implemented a code snippet which includes a placeholder image. However, the implementation seems to not be functioning as ...

Vue.js is not properly synchronizing props in a child component when the parent component is updating the property

When it comes to communication between components, my structure looks something like this: <div id=chat-box> <div class="wrapper"> <div> <chat-header></chat-header> <message-container :chat="chat"></message ...

Tips for reversing a sketch: Creating a timer where the text continuously refreshes causing it to intersect

Currently, I am working on developing a stopwatch that is functional. However, I am facing an issue where the text overlaps itself when it changes due to repetitive drawing. Removing the strokeText and fillText from the interval prevents it from changing a ...

What are the possible complications that could arise from implementing this system for designing web pages?

Feeling frustrated with the limitations and compatibility issues of CSS, I decided to create a new approach for structuring webpages. Instead of relying on CSS, I developed a javascript library that reads layout instructions from XML files and uses absolut ...

Tips for dynamically loading images as needed

I'm working on a simple image zoom jQuery feature using elevateZoom. You can see a Demo example here. The implementation involves the following code: <img id="zoom_05" src='small_image1.png' data-zoom-image="large_image1.jpg"/> <sc ...

What is the best way to extract words from a string within a textarea using javascript?

Currently, I am focused on improving my skills in JavaScript and HTML. In one of my projects, there is a text area where the user inputs a CSV format like this: 17845 hello bye 789 After input, I get 17845,hello,bye,789. Now, the challenge is t ...

The imported package in Node.js cannot be located

I'm encountering an issue when trying to deploy my project on the server. Everything runs smoothly on my PC with no import problems. Thank you for your assistance! Error Message: Error [ERR_MODULE_NOT_FOUND]: Module '/home/igor/backend/alina_edu ...

Maintain the expanded sub-menu when the mouse leaves the area, but a sub-option has been

Implementing a side menu with parent and child options that dynamically display content in the main div on the right when a child option is selected. The parent options are initially shown upon page load, and the child options appear when the mouse hovers ...

What could be causing the state object in React to not be updating correctly? There seems to be a discrepancy between the expanded and

Displayed on the console is a screenshot showing <br><br> I am working with React.js, and the object displayed in the image is an element within an array that is part of the state object. I'm puzzled by what's happening. The object a ...

*NgFor toggle visibility of specific item

Here is a snippet of HTML code that I'm working with: <!-- Toggle show hide --> <ng-container *ngFor="let plateValue of plateValues; let i=index"> <button (click)="toggle(plateValue)">{{i}}. {{ btnText }}</button> ...

What is the best way to integrate jQuery Masonry with ES6 modules?

Attempting to utilize the npm package https://www.npmjs.com/package/masonry-layout Following the installation instructions, I executed: npm install masonry-layout --save Then, in my file, import '../../../node_modules/masonry-layout/dist/masonry.p ...

What is the best way to transform object request data into a string in an Express application using Node.js

I am trying to save the request data from app.get('/') to a variable, but I keep getting an error "TypeError: Converting circular structure to JSON". var express = require('express') var app = express() var bodyParser = require('b ...

How can we trigger a function once an ajax request has finished, without directly interacting with the ajax

I am facing a challenge where I need to trigger a JS function after an ajax call is completed, specifically when filtering posts in WordPress. The issue lies in the fact that the ajax filter tool in use is part of a WordPress plugin that cannot be modified ...

Preserve the authentic picture along with a blur mask that can be dragged and applied to it

Is there a way to preserve the original image while having a draggable blur mask over it? If you want to see an example of a draggable blur mask over an image, you can check out this link: https://codepen.io/netsi1964/pen/AXRabW $(function() { $("#ma ...

What is the syntax for implementing a nested for loop in JavaScript within this particular scenario?

var entries = [ { "item": "something", "steps": [{ "node": {"name": "test0"}, "status": {"name": "test"}, "time": {"name": "test"} },{ "node": {"name": "test1"}, ...

Having Trouble with Click Function: Loading Pages into Div using Jquery/Ajax

Struggling to load content from other pages into a specific div by clicking on a URL link? Despite having previously executed the code successfully, it seems to redirect to the linked page instead of loading in the desired div. Even with an alarm set up as ...

How can we send state updates directly to a conditionally rendered React component?

I am currently developing a React application with a tab section that displays specific components upon clicking on a tab. Initially, I have my parent component: class Interface extends Component { constructor(props) { super(props); ...

Is there a bug in NodeJS that causes an error when a return statement is used with a line feed before the string to be returned?

I am attempting to call a function from a module in order to generate an HTML string. When the function is written with a line feed (LF) between the return statement and the string declaration as shown below, the return value becomes "undefined"... export ...

Guide to crafting your own Chrome browser extension

I have a question that is giving me some trouble. I am working on developing a Chrome extension that will track and update the number of times a specific website has been visited or clicked in a database. I want this count to be displayed before the site i ...