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

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

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

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

Can an onSnapshot event be set up for an array in order to track changes?

In my system, each user is associated with multiple groups. Each user's group membership is stored as an array within their user document. Additionally, there is a tasks collection where each task contains an array of authorizedGroups that correspond ...

AngularJS - $scope.$destroy does not eliminate listeners

I am currently exploring how to develop my own "one-time binding" functionality for AngularJS version 1.2 and earlier. I came across this response which explains the process of creating a custom bindOnce directive. Upon using the provided directive: a ...

Issue with AngularJS form not binding to $http request

<form novalidate class="form-horizontal"> <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <div class="text-capitalize"> </ ...

How can one transform a web-based application into a seamless full-screen desktop experience on a Mac?

"Which software can be utilized to enable a web application to display an icon on the desktop of a Mac computer, while also opening up the web application in a fully immersive full-screen mode that supports all the touch and gesture functionalities provi ...

How can I prevent event propagation in Vuetify's v-switch component?

Currently, I am working with Vuetify and have incorporated the use of v-data-table. Whenever I click on a row within this data table, a corresponding dialog box represented by v-dialog should open. Additionally, each row contains a v-switch element. Howeve ...

Styling for main banner image on large desktop screens and mobile devices

I need help with website design and CSS solutions. Currently, I have a WordPress website with a onepager theme. At the top of the page, there is an image that almost fills the screen along with a title. My concern is how this image behaves with different b ...

Change a camelCase string to ALL_CAPS while adding underscores in JavaScript

Currently, I'm dealing with a situation where I have a list of variables stored in a file that I need to convert into all capital letters and separate them with underscores using JavaScript. The variable pattern looks something like this: AwsKey Aw ...

The importance of manually loading extensions and utilizing Ajax effectively for renderPartial

Within my yii application, I have implemented Tabs and am loading content via ajax using renderPartial(). To prevent redundant script loading, I have set processOutput to false. As a result, I aim to manually load all necessary scripts once on the index pa ...

JavaScript for Verifying Phone Numbers

After extensive research and tutorials, I am still unable to figure out what is going wrong with my work. I have a button that looks like this: Despite Stack Overflow causing some trouble for me, please ignore the missing class as it is there. This is no ...

Merge identical year items into a single entity

I have an array of objects containing car data: [ { year: 2019, company: 'Toyota', quantity: '450' }, { year: 2019, company: 'Ford', quantity: '600' }, { year: 2020, company: ...

What is the best way to organize a data tree in JavaScript for easy parsing on the frontend?

I'm struggling with a unique tree data structure in my code. Each node is represented by an object, and I need to transfer the entire tree to the front-end. Unfortunately, JavaScript's limitation on using objects as keys prevents me from implemen ...

Guide on showcasing jQuery variable values in PHP on a single page

I have some JavaScript and PHP code that I need help with. I want to assign a jQuery variable value to a PHP variable called $nicks, and then echo the value of $nicks on the same page. <script type="text/javascript"> var axel = 131.5678466; < ...

I'm attempting to insert a line break after HTML elements that are being added from JavaScript code inside a `display: flex` div

I'm facing an issue where line breaks are not added after HTML elements are inserted via JavaScript upon clicking a button. For instance, the data from the inputs doesn't get separated even when I click submit multiple times: To illustrate, her ...

Issue with retrieving body class in Internet Explorer on Magento platform. The body class is not being recognized in IE, but works fine in Mozilla and Chrome

<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="<?php echo $this->getLang() ?>" lang="<?php echo $this->getLang() ?>" dir="ltr"> <?php echo $this->getChildHtml('head') ?> <bod ...

Executing a function with arguments within a separate function

I've been working on creating a scheduler function that can randomly call another function with parameters. Here's the JavaScript code I have so far: function scheduleFunction(t, deltaT, functionName) { var timeout; var timeoutID; ...

Ways to eliminate the default margin surrounding an image within a div

Struggling with CSS while building websites is a common issue for me. In my current project, I have encountered a challenge where I placed two images inside a div container. Oddly enough, when I add text to the div, it adjusts its height accordingly. How ...

Detecting the presence of an object in JavaScript or jQuery

My current code is able to save the HTML content of clicked divs in localStorage and then append it to the #result div when the 'Saved Events' button is clicked. However, I am facing a challenge where I need to check if objects already exist in # ...

The closing brackets in PHP substr() function are causing style issues

Here's the scenario: I entered a large amount of content in a text editor (WordPress). Now, I want to display this content on my homepage using PHP queries. In order to limit the content size to 100-200 characters, I used the substr() function i ...

Get the contents inside the window.open using Javascript

First and foremost, I want to acknowledge that I understand the likelihood of this failing due to cross-domain restrictions - just seeking confirmation on that. Here's my approach: I have a window that I open using JavaScript. Subsequently, I make an ...

The for loop encountered an uncaught type error when trying to access the .length property

Currently, I am working on a school project where the task is to create a basic social network posting application using Django and JavaScript. The purpose of using JavaScript is to dynamically load posts onto the webpage and update HTML components. I have ...