Create an interactive HTML table featuring objects as the selected values

I have been attempting to generate an HTML table that is filled with objects.

The goal was to make the table selectable by row (via hover), triggering a function when the row is hovered over.

Here are the table headers stored in an array:

var topTitles = ["Type","Origin","Destination","T","A","G"];

All the data is contained within arrays:

var Type = [];
var Origin = [];
var Destination = [];
var T = [];
var A = [];
var G = [];

I tried modifying some example code, but it was challenging to grasp and implement into a programmatic solution. Is there a simpler way to directly map such data into an interactive table?

function createTable() {
  var table = document.getElementById('matrix');
  var tr = addRow(table);

  for (var j = 0; j < 6; j++) {
    var td = addElement(tr);
    td.setAttribute("class", "headers");
    td.appendChild(document.createTextNode(topTitles[j]));
  }
  for (var i = 0; i < origins.length; i++) {
    var tr = addRow(table);
    var td = addElement(tr);
    td.setAttribute("class", "origin");
    td.appendChild(document.createTextNode(mode[i]));
    for (var j = 0; j < topTitles.length; j++) {
      var td = addElement(tr, 'element-' + i + '-' + j);
      td.onmouseover = getRouteFunction(i,j);
      td.onclick = getRouteFunction(i,j);
    }
  }
}

function populateTable(rows) {
  for (var i = 0; i < rows.length; i++) {
    for (var j = 0; j < rows[i].elements.length; j++) {
      var distance = rows[i].elements[j].distance.text;
      var duration = rows[i].elements[j].duration.text;
      var td = document.getElementById('element-' + i + '-' + j);
      td.innerHTML = origins[i] + "<br/>" + destinations[j];
    }
  }

  if (highlightedCell) {
    highlightedCell.style.backgroundColor="#ffffff";
  }
  
  highlightedCell = document.getElementById('element-' + i + '-' + j);
  highlightedCell.style.backgroundColor="#e0ffff";
  showValues();
}

Answer №1

In my opinion, this method offers the simplest approach to constructing the table without altering your data structure, while also clearly indicating the source of all the data. While it may not be the most optimal code, it should suffice for your current needs.

CodePen

var topTitles = ["Type","Origin","Destination","T","A","G"];
var Type = ["Type1", "type2", "type3"];
var Origin = ["Origin1", "origin2", "origin3"];
var Destination = ["Destination1", "Destination2", "dest3"];
var T = ["t1", "t2","T3"];
var A = ["steaksauce", "a2", "a3"];
var G = ["G1", "G2", "G3"];
var appendString = [];
for(var i =0; i < topTitles.length; i++){
  if(!i){
    appendString.push("<tr><td>" + topTitles[i] + "</td>");
  }
  else if(i === topTitles.length -1){
    appendString.push("<td>" + topTitles[i] + "</td></tr>");
  }
else{
  appendString.push("<td>" + topTitles[i] + "</td>");
    }
}
for(var i =0; i < Type.length; i++){
    appendString.push("<tr><td>" + Type[i] + "</td><td>" + Origin[i] + "</td><td>" + Destination[i] + "</td><td>" + T[i] + "</td><td>" + A[i] + "</td><td>" + G[i] + "</td></tr>");     
}
var table = document.getElementById('table');
table.innerHTML = appendString.join('');

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

Ensuring payload integrity using microrouter: A step-by-step guide

I have utilized this code to develop a microservice const { json, send } = require('micro') const { router, post } = require('microrouter') const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY) console.log(process.e ...

I'm receiving a typeerror when trying to access the uid property of null, even though I don't have any asynchronous code and the users are logged

I am currently working on developing a user profile edit page that redirects users to their unique profile after logging in. However, I keep encountering an error that says Uncaught (in promise) TypeError: Cannot read properties of null (reading 'uid& ...

Is it possible to submit a POST method without using a form?

I am looking to create a button that functions similar to the "Follow" buttons found on social networks. The challenge I face is that I need to refresh the page when the user clicks the button, as the content of the page heavily depends on whether the user ...

Having trouble loading CSS in an express view with a router

I am encountering an issue where I am unable to load my CSS into a view that is being rendered from a Router. The CSS loads perfectly fine for a view rendered from app.js at the root of the project directory. Below is my current directory structure, node_ ...

MUI: How can I resolve the issue of TextField not supporting the number type with maxLength restriction?

I am currently facing an issue with applying maxLength to the TextField component when the type is set to number. Here is my code snippet: const CustomTextField = ({ label, value, maxLength, required, disabled, handleChange, ha ...

Tips for activating text selection in PDF.js

Struggling to enable text selection in PDF.js after successfully displaying a PDF? Seeking a simple example to guide you through the process? Despite trying various approaches, I haven't achieved the desired outcome yet. My current code snippet is a ...

Pass a JavaScript array variable to a PHP script utilizing jQuery Ajax and receive a string output instead of an array

Whenever I attempt to transmit a JavaScript array to a PHP script via Ajax, the output of $_POST['file_paths'] when var_dumped shows up as a string instead of an array. My goal is to have the output in array format rather than in string format. C ...

Building a JavaScript module worker: Step-by-step guide

I am currently facing challenges with implementing web workers in my program. The example provided here is a simplified version of the code structure. There are 4 key files involved: index.html <!DOCTYPE html> <html> <head> <me ...

Avoid an excessive number of XHR/AJAX requests when using the Facebook embedded iframe

I am facing an issue with a Bootstrap Carousel that contains multiple social embeds from Facebook, all of which have videos. The problem is evident on this simple jsfiddle due to the Facebook embed. If you visit this page: https://jsfiddle.net/1L95vqn4/, ...

Ways to conceal text while still allowing it to be read by a screen reader

I am looking for a way to have a text updated by an action without displaying it on the webpage, but still have it announced by screen readers. I tried using display: none and visibility: hidden, however, these properties seem to not be accessible by scr ...

Capture and set the new value of the Datetime picker in MUI upon user's acceptance click

import React from 'react' import { Stack, Typography } from '@mui/material' import { DateTimePicker } from '@mui/x-date-pickers/DateTimePicker' import { renderTimeViewClock } from '@mui/x-date-pickers/timeViewRenderers&ap ...

looking to retrieve the corresponding value of a specific array key

I am trying to determine the value of a complex array, but I keep getting values like 0,1,2,3,4,5 as answers. Here is the code snippet I am using to retrieve the state value of the array: var shardState = Object.keys(mydata.cluster.collections[collection ...

Tips for displaying lesser-known checkboxes upon clicking a button in Angular

I have a form with 15 checkboxes, but only 3 are the most popular. I would like to display these 3 by default and have an icon at the end to expand and collapse the rest of the checkboxes. Since I'm using Angular for my website, I think I can simply ...

Attaching a Stylesheet (CSS) without being inside the HEAD Tag

After seeing numerous inquiries about this topic, I have yet to find the answer I seek. My main question is whether it is feasible to connect an external stylesheet in a location other than the HEAD tag. I am facing this issue because I need to use Conflu ...

Struggling to get the font-weights of the Typography and Button components in the new React with Material-UI to display

In both my previous and most recent React applications, I have the following code snippets: <Typography variant="h6" color="inherit" noWrap > h6. Heading </Typography> <Button type="button" size="large" color="primary" > ...

"Autodesk Viewer: Unlocking the Power of Programmatic Camera Y-Axis Reversal

I have been utilizing the markups core extension to retrieve and restore the viewer state, which has been successful, except for a problem with inversion (only in 3D). When a client interacts with the y-axis specifically, causing the model to flip to revea ...

The conversion from a relative path to an absolute path in Node is producing unexpected results

Hello everyone, I'm facing a problem with the function sendDownload(), specifically with the objPathArray parameter that I am receiving in this format: [{"pathToFile":"./REPORTS/portfolio/onDemand/Portfolio_report_HP_17.08.2021.xlsx","file":"Portfolio ...

Is it possible for the background color to change in a sequence every time the page

I'm having trouble figuring out how to create a sequence that changes the background color every time the page is refreshed. I'm comfortable with basic HTML but not so much with JavaScript or CSS. I'm working on a page where I want the backg ...

Locate the upper and lower limits within an array

I'm currently working on extracting the upper and lower boundaries for a numeric value within an array. const boundaries = [15, 30, 45, 60, 75, 90]; const age = 22; In the given example, the expected result would be: [15, 30] If the value matches ...

Create a background for a dropdown list that appears unreachable, positioned above all other elements

I am encountering an issue with my autocomplete function where the drop down list appears unreadable as it is overlapping other elements on the page. The problem lies in the fact that I did not manually create the drop down list, but rather it is generate ...