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

Facing issues with Handsontable opening within a jQuery UI dialog?

After implementing the Handsontable plugin in multiple tables, everything appears as expected on the parent page. However, when attempting to open a dialog containing a table, the tables do not display properly (only in IE). A demonstration of this issue c ...

Saving a JSON object to a .json file using JavaScript

let project = { Name : "xyz", Roll no 456 }; What is the best way to save the data stored in the project object to a .json file using JavaScript? ...

Incorporating Entrance Animations for Individual Elements within ngView Using AngularJS

Can each content within ngView be animated individually upon entering, rather than the entire View (div) itself? ...

Trouble arises when trying to insert a script tag into a live code editor using HTML

A few days ago, I successfully created a live code editor using the ace 1.2.9 library for my website guides. Now, I'm attempting to create a basic example, but when I try to enter text in the designated text area for the guides, the studio code compil ...

A method for arranging an array of nested objects based on the objects' names

Recently, I received a complex object from an API: let curr = { "base_currency_code": "EUR", "base_currency_name": "Euro", "amount": "10.0000", "updated_date": "2024 ...

JavaScript problem indicating an error that is not a function

Recently, I've delved into the world of JavaScript and am currently exploring JavaScript patterns. I grasp the concepts well but struggle with calling functions that are already in an object. var productValues = 0; var cart = function(){ this. ...

Tips for finding the displayRows paragraph within the MUI table pagination, nestled between the preceding and succeeding page buttons

Incorporating a Material-UI table pagination component into my React application, I am striving to position the text that indicates the current range of rows between the two action buttons (previous and next). <TablePagination ...

Creating interactive JSON objects through the use of JavaScript and AngularJS

When using AngularJS to build a dynamic JSON from server data, I encountered an issue where my current declaration only works if the server data contains one item in the object array. How can I modify this to handle multiple items dynamically? $scope.it ...

Troubleshooting a React Node.js Issue Related to API Integration

Recently, I started working on NodeJs and managed to create multiple APIs for my application. Everything was running smoothly until I encountered a strange issue - a new API that I added in the same file as the others is being called twice when accessed fr ...

Using an array to dynamically input latitude and longitude into a weather API call in PHP

I am currently working on a leaflet map project that showcases the top 10 cities in a selected country. The markers are added dynamically based on the coordinates provided in the $latLng array. For example, when Australia is chosen from the select field, t ...

Tips for incorporating VueJS 2 global components within single file components

As I attempt to utilize a globally registered component (using Vue.component) within a single file component, I consistently encounter the following warning: vue.common.js:2611[Vue warn]: Unknown custom element: <my-component> - did you register the ...

guide on adding a variable to the link_to path

In my attempt to incorporate a variable into the link_to function below: <%= link_to '<button type = "button">Players</button>' .html_safe, live_players_path(:Team => @tmf) %> Whenever I click on this link, it seems to ...

What impact does adding 'ng' in unit tests have on how promises are handled?

Here is an example of a service that utilizes $q.when to wrap a promise from a third-party library: // myService.js angular.module('myApp', []) .service('myService', function($q, $window) { var api = new $window.MyAPI(); this ...

There are times when the `window.location.replace` function does not

I have implemented a Bootstrap Dropdown feature that allows users to select a language for site translation, append the URL with the selected language, and then reload the page. Initially, it works well for the first set of translations like en|es. Howeve ...

When using Node.js with Mongoose, you will receive a single object value instead of multiple values in an array

data=[{ locId: '332wn', locadetails: [ { loc: 'ny', status: true }, { loc: 'ca', status: null ...

Tips for utilizing the Toggle Slider JS functionality

I'm attempting to change a value using a slider in HTML, here is my approach: html file : <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script scr="./scripts.js" ...

Searching for the clicked tr element within a tbody using jQuery

Here is my customized HTML table layout <table> <thead> <tr> <td class="td20"><h3>Client Name</h3></td> <td class="td20"><h3>Details</h3></td> ...

Having trouble retrieving the selected date from the Material-Ui datepicker after the first selection

I am facing an issue with the material-ui dateandtimepicker where I am unable to retrieve the date value on the first select. The value only shows up after the second click, and it's always the previous one. Is there a way to convert the date to a for ...

What could be the reason that the painting application is not functioning properly on mobile devices?

I am facing an issue with my painting app where it works perfectly on desktop browsers but fails to function on mobile devices. I tried adding event listeners for mobile events, which are understood by mobile devices, but unfortunately, that did not solve ...

What is the mechanism by which the useState hook in React determines the calling context?

After transitioning from using class components to functional components in React, I delved into the documentation with keen interest to understand how the useState hook functions. Upon consulting the FAQ page, it was explained that each component has an ...