Creating a table and populating its cells with values all within the confines of a single function

This section of code aims to create 3 arrays by extracting values inputted by the user from a popup menu in the HTML file. These values are then utilized to populate the table displayed below.

var arrM = new Array;      var arrT = new Array;         var arrA = new Array; 
arrM[0] = mod0.mod.value;  arrT[0] = mod0.target.value;  arrA[0] = mod0.actual.value; 
arrM[1] = mod1.mod.value;  arrT[1] = mod1.target.value;  arrA[1] = mod1.actual.value; 
arrM[2] = mod2.mod.value;  arrT[2] = mod2.target.value;  arrA[2] = mod2.actual.value; 
arrM[3] = mod3.mod.value;  arrT[3] = mod3.target.value;  arrA[3] = mod3.actual.value; 
arrM[4] = mod4.mod.value;  arrT[4] = mod4.target.value;  arrA[4] = mod4.actual.value; 
arrM[5] = mod5.mod.value;  arrT[5] = mod5.target.value;  arrA[5] = mod5.actual.value; 
arrM[6] = mod6.mod.value;  arrT[6] = mod6.target.value;  arrA[6] = mod6.actual.value; 
arrM[7] = mod7.mod.value;  arrT[7] = mod7.target.value;  arrA[7] = mod7.actual.value; 
arrM[8] = mod8.mod.value;  arrT[8] = mod8.target.value;  arrA[8] = mod8.actual.value; 
arrM[9] = mod9.mod.value;  arrT[9] = mod9.target.value;  arrA[9] = mod9.actual.value;

The section between the codes above and below (not shown here) is solely for calculating average values and does not interact with the subsequent block.

Next, there is another piece of code responsible for generating a table with rows equal to the number filled out by the user in the popup menu.

var tableGenerator = document.getElementById("tableGenerator");
tbl = document.createElement('table');
tbl.style.width = '500px';
tbl.style.height = '100px';
tbl.style.border = '1px solid black';
tbl.style.margin = '50px';
tbl.style.float = 'left';
if (j < 6) {
    j = 6;
}
for (var a = 0; a < j+1; a++) {
    var tr = tbl.insertRow();
    for (var b = 0; b < 3; b++) {
        if (a == j && b == 3) {
            break;
        } else {
            var td = tr.insertCell();
            td.appendChild(document.createTextNode(""));
            td.style.border = '1px solid black';
            if (a == 0 && b == 0) {
                var newtext = document.createTextNode(Text);
                var celltext = "Year   " + year.value + "  Semester   " + semester.value;
                td.appendChild(document.createTextNode(celltext));
                td.setAttribute('colSpan', '3'); break;
            }
//the following else block is just a template concept that needs implementation to function correctly
              else {
                for (a = 1; a < j; a++) {
                    tbl[a][0] = arrM[a];
                    tbl[a][1] = arrT[a];
                    tbl[a][2] = arrA[a];
                }
            }
        }
    }
}tableGenerator.appendChild(tbl);

I have limited experience with HTML/JS/CSS. Is there any way to access table cell values as if they were an array? Or perhaps there's a more efficient approach to achieve this?

Answer №1

To manipulate table cells in JavaScript, you have a few options. You can either create text nodes and set their content, or use the textContent, innerText, or innerHTML properties to assign values to the cells.

td.textContent = 'Hello'; // Use this property for setting text content.

A good approach is structuring your data in an array that can be looped over. This allows you to perform the same actions in a specific order. For instance:

var data = [
  arrM,
  arrT,
  arrA
];

This way, your arrays are nested within another array. You can then iterate over the data array to create a table row for each array, and a table cell for each item inside the nested arrays.

for (var i = 0; i < data.length; i++) {
  // ... create table row.
  for (var j = 0; j < data[i].length; j++) {
    // ... create table cell and set textContent property.
  }
}

Below is a working example of the concept explained above. It demonstrates how to create a dynamic table using JavaScript. I hope this clarifies the process for you.

function createTable(headers, values) {
  var table = document.createElement('table');
  
  // Build <thead>
  var tableHeader = table.createTHead();
  
  // Create <tr> inside <thead>
  var tableHeaderRow = tableHeader.insertRow();
  for (var i = 0; i < headers.length; i++) {
    // Create <th>
    var tableHeaderCell = document.createElement('th');
    
    // Assign header value from array to <th>
    tableHeaderCell.textContent = headers[i];
    
    // Append <th> to <tr> within <thead>
    tableHeaderRow.appendChild(tableHeaderCell);
  }

  // Build <tbody>
  var tableBody = table.createTBody();
  for (var j = 0; j < values.length; j++) {
    // Create <tr> inside <tbody>
    var tableBodyRow = tableBody.insertRow();

    for (var k = 0; k < values[j].length; k++) {
      // Create <td> inside <tr>
      var tableBodyCell = tableBodyRow.insertCell();
      
      // Set text of <td> to value in array.
      tableBodyCell.textContent = values[j][k];
    }
  }

  // Add <table> to the <body>
  document.body.appendChild(table);
}

var titles = [
  'One',
  'Two',
  'Three'
];

var characters = [
  ['Batman', 'Robin', 'Batgirl'],
  ['Joker', 'Two-Face', 'Poison Ivy'],
  ['James Gordon', 'Alfred Pennyworth', 'Clayface']
];

createTable(titles, characters);

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

What is the process for assigning a serial number to each row in the MUI DataGrid?

Initially, the server is accessed to retrieve some data. After that, additional data is added. While the data does not contain an ID, the form must still display a serial number. const columns: GridColDef[] = [ { field: 'id' ...

Display Material Popup in Angular before user leaves the page

My goal is to display an Angular Material Dialog Box (Popup window) when the user clicks the Chrome Window Close button. The Dialog modal should prompt the user if they want to save changes or cancel. However, the modal only appears for a brief moment and ...

Creating audio streams using react-player

I am currently working on integrating the react-player component from CookPete into my website. However, I am facing a challenge in setting up multiple audio streams. Additionally, I want to include both DASH and HLS video streams but adding them as an arr ...

Steps for submitting a form once all inputs have been verified

$('#f_name, #l_name').change(function(){ if($(this).val().length < 2) { $(this).css('border', '1px solid red'); alert('names must be at least 2 symbols'); check ...

Enable or disable dropdown based on selected radio button status

I need the dropdown to be disabled unless the radio button labeled prov is selected. It should only be enabled when prov is chosen. I attempted to create a demo, but it's not functioning correctly and I can't figure out why. HTML: <td colsp ...

Moving through divisions that share a common class name using jquery

I am experimenting with a plugin that allows me to attach popups to images. My goal is to enable navigation between all popups using previous and next buttons upon clicking on a popup. Below is the element when it's displayed: <div class="imp-too ...

How odd! Using window.location or location.replace redirects to the page and then reverses back!

While in debug mode, I am able to track which page is being accessed. Interestingly, whenever I use window.location or window.location.replace(..), the browser redirects to the specified page but then quickly returns to the original one! This strange beh ...

"Displaying a popup message prompting users to refresh the page after clicking

I need to implement a feature where the page refreshes only after the user clicks the "OK" button on a dialog box that appears once a process is completed. The issue I'm facing is that in my current code, the page refreshes immediately after the proc ...

"Please ensure that the field values in MessageEmbed are not left empty" stated discord.js

I've been working on a Discord bot using node.js, and I've encountered an issue with my kick and ban commands. I've tried to incorporate Discord embeds, but I keep running into this problem. Can anyone assist me with this? Here is the code ...

Adjust the jQuery and PHP script to retrieve both the ID and text content to populate an OPTION element

I have a basic DROPDOWN list: <select class='form-control' id='builders' name='builder_id'> <option value="1">Java</option> <option value="2">Python</option> </select> I am looking ...

Angular.js: Applying a style to elements beyond the current scope based on the selected route

I'm looking to dynamically add classes outside of the current scope. Specifically, I need to add classes to the header, main, and footer elements as shown below: <header class="{{pageClass}}"></header> <main class="{{pageClass}}" ng-vi ...

Artwork expanding incorrectly on HTML canvas

I'm encountering an issue while attempting to draw on an HTML canvas. I've specified 50 circles and multiple lines within a canvas of size 1000x1000 px, but not all circles are appearing as expected. My assumption is that the elements are being ...

Encountering a Node.js issue when attempting to properly sanitize data before inserting it into MySQL

This is a snippet of code that I am using to insert data into a MySQL table. Before running the query, I escape the values like so: const mysql = require('mysql'); const R = require('ramda'); class Repository { constructor(connectio ...

Utilizing multiple class names in Material UI with identical definitions

When working with traditional CSS, it is common to define shared properties between classes like this: .classA,.classB{ background-color: black; } In Material UI and using theming, the equivalent would be: styles = (theme)=>({ classA:{ ba ...

What is the best way to ensure a bottom tooltip stays perfectly aligned with the right edge of its corresponding element?

Currently, I am trying to implement a tooltip above my progress bar. However, the small tooltip that I have is not functioning correctly... This is how it currently appears: https://i.sstatic.net/ZJUyT.png I need the tooltip to display above the white d ...

Modify the contents of a textbox by editing the text as you type

Text within the text box follows this format: login -u username -p password When entering this text, I want to substitute 'password' with a series of '*'s equal in length. For example: 'login -u <a href="/cdn-cgi/l/email-prot ...

Sorting functionality malfunctioning after dynamically adding new content using AJAX

Greetings to all, I have a question about my views. 1- Index 2- Edit In the index view, I have a button and AJAX functionality. When I click the button, it passes an ID to the controller which returns a view that I then append to a div. The Edit view con ...

Updating data in a table upon submission of a form in Rails

In my Rails 3.2 application, I am displaying a table of results using the @jobs variable passed to the view from a SQL query. I want to add a button that will trigger a controller action when clicked. The action should perform some database operations and ...

Obtain the bounding box of an SVG element while it is not visible

I've been grappling with this issue for more than a day now, but I'm still unable to find a solution. My challenge lies in the need to scale an SVG image for responsive design purposes. Since I have to manipulate the SVG code on the client side, ...

What are the steps for leveraging a proxy with NodeJS and Selenium?

While researching the topic on proxies in the documentation, I came across a method to set up a proxy while building a driver like this: var driver = new webdriver.Builder() .withCapabilities(webdriver.Capabilities.chrome()) .setProxy(proxy.manual ...