0

I am using ParcelJS V2. I have the following code that gets data from an HTML table. Every <td> in the cell consists of an <input> tag and the getElementById refers to the ID of the input tag.

getCount.js

let rowCount = document.getElementById("left-col__table").rows.length;

let dataExport = []
let tuple = []

let i

function collectData() {

    for (i = 0; i < rowCount - 2; i++) {
        
        console.log("RowCount: " + rowCount)
        
        tuple.push(document.getElementById("x-in-" + i.toString()).value)
        tuple.push(document.getElementById("y-in-" + i.toString()).value)

        console.log(tuple);

        dataExport.push(tuple)

        tuple = []
    }

    console.log("DataExport:" + dataExport.toString())
}

export default collectData

script.js

import collectData from '....'

collectData()

When I check my console, there isn't log from the collectData function.

This FOR loop works fine when I use it in my script.js but doesn't work when I export and then import into script.js.

Are there any ways to export loops using ParcelJS?

Praanto
  • 216
  • 4
  • 14
  • can you please show us proper example of how you doing it cause this is not helping out. – kunal panchal Mar 25 '21 at 17:43
  • @kunalpanchal I'm sorry it wasn't clear first. I tried clarifying further. Thanks – Praanto Mar 25 '21 at 18:58
  • 1
    I don't think exporting a `function` that relies on the DOM being available at the time of the import is a good idea (`let rowCount = document.getElementById("left-col__table").rows.length;`). Move your variable declaration inside the function. – connexo Mar 25 '21 at 19:21
  • @connexo hi thanks for the tip. My function works now after I moved my variable into my function. – Praanto Mar 25 '21 at 19:34

2 Answers2

2

Move

let rowCount = document.getElementById("left-col__table").rows.length;

inside your function collectData() {.

At the time of bundling the DOM is unavailable, rendering your rowCount undefined.

When your function is being executed, your loop end condition checks

0 < undefined - 2

undefined - 2 results in NaN.

0 < NaN

is false, so your loop never runs.

connexo
  • 53,704
  • 14
  • 91
  • 128
1

Try this out.

getCount.js

function collectData() {

  let rowCount = document.getElementById("left-col__table").rows.length;

  let dataExport = []
  let tuple = []

  let i

  for (i = 0; i < rowCount - 2; i++) {

    console.log("RowCount: " + rowCount)

    tuple.push(document.getElementById("x-in-" + i.toString()).value)
    tuple.push(document.getElementById("y-in-" + i.toString()).value)

    console.log(tuple);

    dataExport.push(tuple)

    tuple = []
  }

  console.log("DataExport:" + dataExport.toString())
}

export default collectData
kunal panchal
  • 798
  • 5
  • 21