0

I am trying to load csv/txt data to load to select box. I have tried this script and failed to load data to select which is a multiple select box This is my altered script

  $("#upload").bind("click", function() {
    var regex = /^([a-zA-Z0-9\s_\\.\-:])+(.csv|.txt)$/;
    if (regex.test($("#fileUpload").val().toLowerCase())) {
      if (typeof(FileReader) != "undefined") {
        var reader = new FileReader(),
          sel = $("<select id='s'>"),
          separator = ';',
          rows,
          rowLength;

        reader.onload = function(e) {
          rows = e.target.result.split(/[\r\n|\n]+/);
          rowLength = rows.length;

          for (var i = 0; i < rowLength; i++) {
            var row = $("<option>"), cells = rows[i].split(separator), cellLength = cells.length, cell;

            for (var j = 0; j < cellLength; j++) {
                $(cell).val(cells[j]);
                row.append(cell);
            }


            sel.append(row);
          }
          $("#dvCSV").html('');
          $("#dvCSV").append(sel);
        }
        reader.readAsText($("#fileUpload")[0].files[0]);
      } else {
        alert("This browser does not support HTML5.");
      }
    } else {
      alert("Please upload a valid CSV file.");
    }
  });

This loads blank select box. How load this (option value and text must be same)

And to this, I want to skip a row, if any of the column is blank

Community
  • 1
  • 1
Ranjan
  • 3
  • 2

1 Answers1

0

Actually, I think this would be easier with Python and its CSV module if you can set that up in your server.

However, with JavaScript, you can use PapaParse and iterate using that.

As a last option, look at this answer

What are delimiters?

The answer I posted allows for a value delimiter. This is a way of including values with commas in a CSV file.

For example, here is a random CSV row

USERNAME, PASSWORD
JOHN,"asd,ddd"

As you can see, the maker used an extra comma in the PASSWORD field and hence, used inverted commas to escape it.

In the end, I strongly recommend Python or some similar scripting language for this purpose. Using JavaScript is not really the most efficient method.

For the code, once you have your row, MAKE SURE TO ESCAPE THE DELIMITER.

Then, your code will work (example written in Python)

for x in row: #going through each element of the row
    if x != "":
        myRowArray.add(row)
Community
  • 1
  • 1
rassa45
  • 3,482
  • 1
  • 29
  • 43