Swapping values between HTML tables and arrays with the power of JavaScript

I have a unique table structure that I need help with:

https://i.sstatic.net/fr7oJ.png

My current table has 2 rows and multiple columns, but I want to change it to have 2 columns and multiple rows like this:

https://i.sstatic.net/uhkp9.png

To create the table, I am using two arrays named milestone and milestoneDate. The values from these arrays are then appended to a div with the id meilensteine. For example, milestone contains: "1. MS: Beginn, 2. MS: Start, 3. MS: Meilensteine, 4. MS: Testung" while milestoneDate contains: "06.09.2021, 07.09.2021, 08.09.2021, 09.09.2021"

Here is the HTML snippet:

<div>
    <div>
        <strong><u>Meilensteine</u></strong>
    </div>

    <p></p>
    <div id="meilensteine">
    </div>

    <p></p>
</div>

And here is the JavaScript code:

var cycleArr = [milestone, milestoneDate];

var strTable = "";
if (cycleArr.length != "0"){ 
    for(var i = 0; i < cycleArr.length; i++) {
        strTable += "<tr>"
        for(var j = 0; j < cycleArr[i].length; j++) {
            strTable += "<td>";
            strTable += cycleArr[i][j];
            strTable += "</td>";
        }
        strTable += "</tr>";
    }
} else {
    strTable = "Es gibt derzeit keine Meilensteine. Definieren Sie gerne die Meilensteine für das Projekt hier.";
}
$('#meilensteine').append(strTable);

Despite my attempts, I haven't been able to make it work as desired.

Answer №1

If you're looking to accomplish this task effortlessly, here's a clever workaround!

1. Start by creating a template using template literals in javascript:

const tableRowTemplate = `<tr><td>Stuff for column 1</td><td>stuff for column 2</td></tr>`;

2. Populate the template dynamically with content from two arrays:

const milestone = ['1. MS: Beginn','2. MS: Start','3. MS: Meilensteine','4. MS: Testung']
const milestoneDate = ['06.09.2021','07.09.2021','08.09.2021','09.09.2021']
for(let i = 0; i<milestone.length; i++){
    const tableRowTemplate = `<tr><td>${milestone[i]}</td><td>${milestoneDate[i]}</td></tr>`;
}

3. Insert this template into the table and witness it live:

const milestone = ['1. MS: Beginn', '2. MS: Start', '3. MS: Meilensteine', '4. MS: Testung']
const milestoneDate = ['06.09.2021', '07.09.2021', '08.09.2021', '09.09.2021']
for (let i = 0; i < milestone.length; i++) {
  const tableRowTemplate = `<tr><td>${milestone[i]}</td><td>${milestoneDate[i]}</td></tr>`;
  document.getElementById("table").innerHTML += tableRowTemplate
}
<div>
  <div>
    <strong><u>Meilensteine</u></strong>
  </div>

  <p></p>
  <div id="meilensteine">
  </div>

  <p></p>
  <table id="table"></table>
</div>

Hopefully, this methodology proves beneficial in addressing your concern.

Answer №2

const tasks = [ "Task 1", "Task 2", "Task 3", "Task 4" ];
const taskDates = [ "06.09.2021", "07.09.2021", "08.09.2021", "09.09.2021" ];

let tds = "", tdsd = "";
for (let i=0; i<tasks.length; i++) {
  tds += `<td>${tasks[i]}</td>`;
  tdsd += `<td>${taskDates[i]}</td>`;  
}
document.getElementById("taskrow").innerHTML = tds;
document.getElementById("dateRow").innerHTML = tdsd;


let tableRows = "";
for (let i=0; i<tasks.length; i++) {
  tableRows += `<tr><td>${tasks[i]}</td><td>${taskDates[i]}</td></tr>`;  
}
document.getElementById("tworows").innerHTML = tableRows;
<h3>2 rows</h3>
<table id="tworows" border="1">
 <tr id="taskrow"></tr>
 <tr id="dateRow"></tr>
</table>

<h3>2 columns</h3>
<table id="twocols" border="1"></table>

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

Ways to automatically insert an icon within a textarea

While attempting to insert an image inside a textarea, I discovered that it seems impossible without using the contenteditable ="true" attribute of a textarea. However, upon visiting the diaspora site, I found out that this can indeed be achieved. I am uns ...

Update a mySQL table using dynamic input from a table

I'm facing challenges updating a mysql database with a dynamic table that allows me to add or remove rows before submitting the form. While I can make it work with hardcoded values, I struggle when trying to update with a while loop. It just doesn&ap ...

Choose the Nth option in the dropdown list using programming

Currently, I have a script that dynamically populates a select box with unknown values and quantities of items. I am looking to create another script that mimics the action of selecting the Nth item in that box. Despite my research, I have been unable to ...

Tips for concealing the final click (add) tab after it has been clicked and revealing the hidden (add) button when the user clicks on the remove button

I have created a form where users can add tests. Everything is working smoothly but I want the previous "Add Another Test" field to be removed when the user clicks on it and a new field to be shown. Everything is running well, but the issue is that when t ...

Aligning images of varying sizes

I have implemented a PHP script that automatically resizes images proportionally to fit within a given height and width. For example, if the original picture is 200x100px and the target box is 180x180px, the resized image will be 180x90px. Although this s ...

PHP and Bootstrap combine in this dynamic carousel featuring thumbnail navigation

Looking to create a dynamic bootstrap carousel with image thumbnails at the bottom? After exploring various code snippets and solutions, I stumbled upon this link. While the code worked, I found the thumbnails to be too small. Below are the functions I use ...

Using the object value to map an array and populate the resulting elements

i have a function const [jobs, setJobs] = useState([]) const addJob = (title, role) => { const newJobs = [...jobs, { title, role}] setJobs(newJobs) } whenever a form is submitted, the addJob function creates state data containing ...

Testing actual HTTP requests in unit and integration tests with AngularJS

Attempting a request that was not mocked using $httpBackend.when in an Angular 1.x unit/integration test will lead to an error: Error: Unexpected request: GET /real-request Is there a way to perform actual HTTP requests with ngMock and the Karma+Jasmin ...

Is it possible to create a looped GLTF animation in three.js using random time intervals?

I am currently exploring the world of game development with Three.js and have a specific query regarding animating a GLTF model. Is it possible to animate the model at random intervals instead of in a continuous loop? In the game I am creating, players wil ...

Node inadvertently triggers functions with similar names from a different module

Currently, I am developing a web application using Node and the Express framework. Within my project, I have organized two modules, CreateAccountService.js and LoginService.js, in the "service" directory. Each module currently only exports one function. ...

Simulated script in a different component

I am looking to simulate the functionality of Amazon AWS S3 getObject The specific code I aim to test is located in helper.js var AWS = require('aws-sdk'); var s3 = new AWS.S3(); exports.get_data_and_callback = function(callback, extra){ s3. ...

blur event triggered on a cell within a table

Currently, I am using the code snippet below to populate data using a data table. My goal is to be able to edit the data in one of the columns and then validate the value after editing using the onblur event. I attempted to call the onblur event on the t ...

Stylish Card Design

Below is the CSS code: *{margin:0; padding:0; box-sizing:border-box; } img{ display:block; max-width:100%; height:auto; } html{ scroll-behavior:smooth; } body{ min-height:100vh; font-family:fantasy; font-size:1.12 ...

Having trouble getting Vue-Select2 to display properly in Vuejs?

After setting up the vue3-select2-component and following their instructions, I encountered an issue where the component was not displaying in the output on the html page, even though the code for it was present in the source code. For context, I am using ...

JavaScript event handler for dynamic button click

I am creating a unique button dynamically for each row in a table to handle deletions. I am assigning the id of the button with the key of the row, allowing me to retrieve it later when clicked. Since all buttons share the same function, passing the specif ...

Creating a Build System for JavaScript in Sublime Text

While working on developing an application using node.js, I decided to create a JavaScript build system in Sublime Text 3 on my Ubuntu OS. I made a new build system file named nodey.sublime-build with the following contents: { "cmd": ["node","$file"," ...

The custom HTML menu implementation is causing the jQuery autocomplete to lose its "Select" functionality

Seeking assistance in implementing jQuery autocomplete with a custom drop down menu. I have managed to customize menu items using the data()._renderItem method (which is currently commented out), however, this approach disables the menu "Select" function ...

React error: Updating state is only allowed on mounted or mounting components

I'm encountering this Error/Warning message in my console: The error message says: setState(...): Can only update a mounted or mounting component. Addressing the Component Mounting Process When it comes to mounting the component, here's the r ...

simulated xhr server along with the locales in polymer appLocalizeBehavior

Currently, I am in the process of developing a web frontend utilizing Polymer. Within my web component, I incorporate various other components such as paper-input or custom web components. To facilitate testing for demonstration purposes, I have integrated ...

What is the best way to determine if two external values are equal within a mongodb criteria object?

Consider the following collection: {id: 1, name:"abc"}, {id: 2, name:null} When testing a property, I typically use this method: db.collecton.find({name:"abc"}, {name:1}); // This will return the first document. Now, I want to incorporate two external ...