santosh
santosh

Reputation: 892

How to perform multiple for loops at same time in Javascript

I want when anybody clicks "Add Value" table rows should be created with the textarea values(Please refer Image for more understanding!). I am facing problem will doing for loop, I want all for loop condition should perform at same time. Please tell me how I can perform all for loops condition at same time.

[Image][1]

[JsFiddle][2]

Code:

<div dir="ltr" style="text-align: left;" trbidi="on">
   <html>
      <head>
         <style>
            table, th, td {
            border: 1px solid black;
            border-collapse: collapse;
            }
            th, td {
            padding: 15px;
            text-align: left;
            }
         </style>
      </head>
      <body>
         <center>
            <textarea cols="50" id="input1" rows="10">
              1
              2
              3
              4
              5
            </textarea>
            <br />
            <textarea cols="50" id="input2" rows="10">
              1
              2
              3
              4
              5
            </textarea>
            <br />
            <textarea cols="50" id="input3" rows="10">
              1
              2
              3
              4
              5
            </textarea>
            <br />
            <textarea cols="50" id="input4" rows="10">
              1
              2
              3
              4
              5
            </textarea>
            <br />
            <textarea cols="50" id="input2" rows="10">
              1
              2
              3
              4
              5
            </textarea>
            <br />
            <button onclick="myFunction()">Add Values</button><br /><br />
            <table id="myTable">
               <tr>
                  <th>Sr No</th>
                  <th>Contact</th>
                  <th>Country</th>
                  <th>Sr No</th>
                  <th>Sr No</th>
               </tr>
            </table>
            <br>
            <button id="btnCopy">
            Copy Table!</button><br>
         </center>
      </body>
      <script>
         function myFunction() {
         
           const values1 = document.querySelector('#input1')
           .value.trim().split('\n');
           
           const values2 = document.querySelector('#input2')
           .value.trim().split('\n');
           
           const values3 = document.querySelector('#input3')
           .value.trim().split('\n');
           
             const values4 = document.querySelector('#input4')
           .value.trim().split('\n');
           
             const values5 = document.querySelector('#input5')
           .value.trim().split('\n');
           
           const table = document.querySelector('#myTable');
           
           for (const value1 of values1 && const value2 of values2 && const value3 of values3 && const value4 of values4 && const value5 of values5)
             table.innerHTML += `
         <tr><th>${value1}</th><td><b>${value2}</b></td><td>${value3}</td><td>${value4}</td><td>${value5}</td></tr>
         `;  
             
           
         }
         
      </script>
   </html>
</div>

Upvotes: 0

Views: 101

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074425

It sounds like you're trying to access parallel arrays. This is a situation where you want a traditional for loop rather than a for-of loop:

const len = Math.max(values1.length, values2.length, values3.length, values4.length, values5.length);
for (let i = 0; i < len; ++i) {
    table.innerHTML += `
<tr><th>${values1[i]}</th><td><b>${values2[i]}</b></td><td>${values3[i]}</td><td>${values4[i]}</td><td>${values5[i]}</td></tr>
`; 
}

You might want || "" to use "" instead of undefined if one or more of the arrays isn't as long as the longest one:

const len = Math.max(values1.length, values2.length, values3.length, values4.length, values5.length);
for (let i = 0; i < len; ++i) {
    table.innerHTML += `
<tr><th>${values1[i] || ""}</th><td><b>${values2[i] || ""}</b></td><td>${values3[i] || ""}</td><td>${values4[i] || ""}</td><td>${values5[i] || ""}</td></tr>
`; 
}

Although looking at that string, I think I'd probably do the function differently:

function myFunction() {
    const allValues = [
        document.querySelector('#input1').value.trim().split('\n'),
        document.querySelector('#input2').value.trim().split('\n'),
        document.querySelector('#input3').value.trim().split('\n'),
        document.querySelector('#input4').value.trim().split('\n'),
        document.querySelector('#input5').value.trim().split('\n'),
    ];
    const table = document.querySelector('#myTable');
    const len = Math.max(...allValues.map(values => values.length));
    let html = "";
    for (const values of allValues) {
        // Fill in any blanks
        values.fill("", values.length, len);
        // Add this row
        html += "<tr>" + values.map((v, index) => {
            const tag = index === 0 ? "th" : "td";
            return `<${tag}>${v}</${tag}>`;
        }).join("") + "</tr>";
    }
    // Append to the table (all at once)
    table.insertAdjacentHTML("beforeend", html);
}

Using += with innerHTML is generally poor practice. When you do that, the browser has to spin through your existing DOM structure building a string of HTML to pass to your JavaScript code, and then take what you JavaScript code gives back, tear down the complete contents of your DOM structure, and replace it with new elements created by parsing the new string.

Upvotes: 1

Related Questions