1

I found a javascript that reads a CSV file. I can run this code successfully and get the CSV file data imported in a div. However, there are six columns in CSV file. I only need to get column 1 and column 3 from CSV file and display in div.

<script type="text/javascript">
    function Upload() {
        var fileUpload = document.getElementById("fileUpload");
        var regex = /^([a-zA-Z0-9\s_\\.\-:])+(.csv|.txt)$/;
        if (regex.test(fileUpload.value.toLowerCase())) {
            if (typeof (FileReader) != "undefined") {
                var reader = new FileReader();
                reader.onload = function (e) {
                    var table = document.createElement("table");
                    var rows = e.target.result.split("\n");
                    for (var i = 0; i < rows.length; i++) { var cells = rows[i].split(","); if (cells.length > 1) {
                            var row = table.insertRow(-1);
                            for (var j = 0; j < cells.length; j++) {
                                var cell = row.insertCell(-1);
                                cell.innerHTML = cells[j];
                            }
                        }
                    }
                    var dvCSV = document.getElementById("dvCSV");
                    dvCSV.innerHTML = "";
                    dvCSV.appendChild(table);
                }
                reader.readAsText(fileUpload.files[0]);
            } else {
                alert("This browser does not support HTML5.");
            }
        } else {
            alert("Please upload a valid CSV file.");
        }
    }
Load Summary File

I got another code from another website that reads through "table" but seems function is not able to recognize "table" element:

<script>
function showTableData() {
    document.getElementById('info').innerHTML = "";
    var myTab = document.getElementById('table');

    // LOOP THROUGH EACH ROW OF THE TABLE AFTER HEADER.
    for (i = 1; i < myTab.rows.length; i++) {
        
        // GET THE CELLS COLLECTION OF THE CURRENT ROW.
        var objCells = myTab.rows.item(i).cells;

        // LOOP THROUGH EACH CELL OF THE CURENT ROW TO READ CELL VALUES.
        for (var j = 0; j < objCells.length; j++) {
            info.innerHTML = info.innerHTML + ' ' + objCells.item(j).innerHTML;
            
            var thisitem = objCells.item(j).innerHTML
            if (thisitem == "01") {
                alert(thisitem);
                objCells.item(j).style.color = "red";
            }            
        }
        
        info.innerHTML = info.innerHTML + '<br />';     // ADD A BREAK (TAG).
        
    }
}

My questions:

  1. How do I apply a class to dynamically created Table?
  2. How do I check column1 and column3 data and then change the style.

My biggest frustration is that I am not able to access "Table" element that was created dynamically.

Thank You Nratawa

Matt
  • 5,315
  • 1
  • 30
  • 57
nratawa
  • 29
  • 7

1 Answers1

0

How to access table:

To access the table, you need to make sure the table has an id of table due to this line of code var myTab = document.getElementById('table');. The solution for this is setting the id on the table created like so:

var table = document.createElement("table");
table.id = 'table' // now document.getElementById('table') works because the table has matching id

How to add class to table:

To add a class to the dynamically created table, you can use the classList api.

Example: table.classList.add('tableClass')

How to only collect columns 1 and 3:

If you only want columns 1 and 3, you can use a combo of an array and continue in the cells loop

function Upload() {
    const columns = [0, 2] // represents allowed column 1 and 3 in index form

    var fileUpload = document.getElementById("fileUpload");
    var regex = /^([a-zA-Z0-9\s_\\.\-:])+(.csv|.txt)$/;
    if (regex.test(fileUpload.value.toLowerCase())) {
        if (typeof (FileReader) != "undefined") {
            var reader = new FileReader();
            reader.onload = function (e) {
                var table = document.createElement("table");
                var rows = e.target.result.split("\n");
                for (var i = 0; i < rows.length; i++) { var cells = rows[i].split(","); if (cells.length > 1) {
                        var row = table.insertRow(-1);
                        for (var j = 0; j < cells.length; j++) {
                            // ignore columns that are not allowed
                            if (!columns.includes(j)) {
                              continue
                            }

                            var cell = row.insertCell(-1);
                            cell.innerHTML = cells[j];
                        }
                    }
                }
                var dvCSV = document.getElementById("dvCSV");
                dvCSV.innerHTML = "";
                dvCSV.appendChild(table);
            }
            reader.readAsText(fileUpload.files[0]);
        } else {
            alert("This browser does not support HTML5.");
        }
    } else {
        alert("Please upload a valid CSV file.");
    }
}
ChrisF582
  • 169
  • 6
  • Thank you very much! It has worked great. However, the returned output from CSV shows double quotes symbol around value. For example it shows "Dave". I would only like to show Dave. – nratawa Apr 15 '21 at 11:53
  • 1
    There are a few ways to do that using String api (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String). One simple way is with the `String.replace` method and regex although note that this strips ALL double quotes, not just the ones at start and end. `cell.innerHTML = cells[j].replace(/"/g, '');`. Reference this StackOverflow question for a more in depth solution: https://stackoverflow.com/questions/19156148/i-want-to-remove-double-quotes-from-a-string – ChrisF582 Apr 15 '21 at 18:45
  • Awesome! Thanks! – nratawa Apr 16 '21 at 03:18