0

I am trying to have a .csv file read to a drop down in HTML. Currently with the code below, my drop down is not being populated. I am not sure if it's because of my path or if I am not calling it correctly in my HTML. Any advice?

code (I found this code as an example and was trying to implement it to test with no luck):

(function() {

  var csv_path = "C:\Users\userName\Documents\Qlik\Request Page\streamFileTEST.csv";

  var renderCSVDropdown = function(csv) {
    var dropdown = $('select#selectStyle');
    for (var i = 0; i < csv.length; i++) {
      var record = csv[i];
      var entry = $('<option>').attr('value', record.someProperty);
      console.log(record);
      dropdown.append(entry);
    }
  };

  $.get(csv_path, function(data) {
    var csv = CSVToArray(data);
    renderCSVDropdown(csv);
  });

}());

function CSVToArray(strData, strDelimiter) {

  strDelimiter = (strDelimiter || ",");

  var objPattern = new RegExp((
    "(\\" + strDelimiter + "|\\r?\\n|\\r|^)" +

    "(?:\"([^\"]*(?:\"\"[^\"]*)*)\"|" +

    "([^\"\\" + strDelimiter + "\\r\\n]*))"
  ), "gi");


  var arrData = [
    []
  ];

  var arrMatches = null;

  while (arrMatches = objPattern.exec(strData)) {

    var strMatchedDelimiter = arrMatches[1];

    if (strMatchedDelimiter.length && strMatchedDelimiter !== strDelimiter) {

      arrData.push([]);

    }

    var strMatchedValue;

    if (arrMatches[2]) {

      strMatchedValue = arrMatches[2].replace(new RegExp("\"\"", "g"), "\"");

    } else {
      strMatchedValue = arrMatches[3];

    }

    arrData[arrData.length - 1].push(strMatchedValue);
  }

  return (arrData);
}
#selectStyle {
  height: 29px;
  overflow: hidden;
  width: 470px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img class="imgQlik" src="qlik-sense-logo.png">
<hr>
<form action="mailto:emailAddress.com" method="post" enctype="text/plain">
  <div>
    <table id="requestTable">
      <tbody>
        <tr>
          <td class="tdLabel">
            <label>Name:</label>
          </td>
          <td class="tdInput">
            <input type="text" id="user-name" name="display-name" pattern="[A-Za-z\s]+" maxlength="50" minlength="2" required>
          </td>
        </tr>
        <tr>
          <td class="tdLabel">
            <label>Stream List:</label>
          </td>
          <td>
            <select id="selectStyle" name="streamlistselect"></select>
          </td>
        </tr>
      </tbody>
    </table>
  </div>
  <input class="buttonRequest" type="submit" value="Submit Request">

</form>
Andrew Lohr
  • 5,380
  • 1
  • 26
  • 38

2 Answers2

1

1 major concept- You cannot read the filesystem through the browser due to security concerns. So doing a get request to C:\Users\userName\.... will not work.

Then just a few small things after that:

  1. The user needs to upload the file themselves, so I added an input of type file for your users to upload their csv files. I limited it to only csv files with accept=".csv" attribute

  2. Then you need a way to handle that file, I put together handleFile() function for you that reads in the data from the uploaded csv file using FileReader.

  3. Next we call renderCSMDropdown with the csv data and I updated your loop a bit to loop through the elements split by a "," and append an option node to your select element. I also added a text attribute to the options so you can see them.

$("#inputFile").on("change", handleFile);

var renderCSVDropdown = function(csv) {
  var dropdown = $('#selectStyle');
  var elements = csv.split(",");
  for (var i = 0; i < elements.length; i++) {
    var record = elements[i];
    var entry = $('<option>', {value: record, text: record})
    dropdown.append(entry);
  }
};

function handleFile() {
    var file = $(this).prop('files')[0];
    var fileReader = new FileReader();
    fileReader.onload = function (evt) {
      renderCSVDropdown(evt.target.result);
    };
    fileReader.readAsText(file, "UTF-8");
}
#selectStyle {
  height: 29px;
  overflow: hidden;
  width: 470px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img class="imgQlik" src="qlik-sense-logo.png">
<hr>
Choose csv file: <input type="file" id="inputFile" accept=".csv"><br/><br/>
<form action="mailto:emailAddress.com" method="post" enctype="text/plain">
  <div>
    <table id="requestTable">
      <tbody>
        <tr>
          <td class="tdLabel">
            <label>Name:</label>
          </td>
          <td class="tdInput">
            <input type="text" id="user-name" name="display-name" pattern="[A-Za-z\s]+" maxlength="50" minlength="2" required>
          </td>
        </tr>
        <tr>
          <td class="tdLabel">
            <label>Stream List:</label>
          </td>
          <td>
            <select id="selectStyle" name="streamlistselect"></select>
          </td>
        </tr>
      </tbody>
    </table>
  </div>
  <input class="buttonRequest" type="submit" value="Submit Request">

</form>
Andrew Lohr
  • 5,380
  • 1
  • 26
  • 38
  • I can't have the user upload their own file, I need to have it so it is read from a location. Is their a way to do that without the security concern? – beginnerDeveloper Aug 21 '18 at 16:34
  • can you change the location of the file? – PerrinPrograms Aug 21 '18 at 16:36
  • @PerrinPrograms I can, this is just a test on my local machine, the permanent file location will be from a shared folder from the server that gets automatically updated when the data changes. – beginnerDeveloper Aug 21 '18 at 16:40
  • @beginnerDeveloper not really, you can try some steps in here https://stackoverflow.com/questions/14446447/how-to-read-a-local-text-file but for the most part it probably not work. – Andrew Lohr Aug 21 '18 at 16:41
  • so you can move the file to the directory of the project itself and will be able to access it, Are you running it from a server? If not, you can run a small python server like this: https://developer.mozilla.org/en-US/docs/Learn/Common_questions/set_up_a_local_testing_server then you can access your file like. localhost:8000/your_file.csv – PerrinPrograms Aug 21 '18 at 16:46
  • the other thing you can do is allow local file access in chrome. Create a new chrome shortcut and in the properties after target, add this line, "--allow-file-access-from-files". in order for this to work, all other instances of chrome need to be closed. https://stackoverflow.com/questions/18586921/how-to-launch-html-using-chrome-at-allow-file-access-from-files-mode this is definitely a security issue though and should only be turned on for testing. – PerrinPrograms Aug 21 '18 at 16:49
0

To populate dropdown, we need to set inner html of

Try below, also put the code inside document.ready function

var entry = $('<option>').html('value', record.someProperty);

Fiddle - https://jsfiddle.net/o2gxgz9r/65565/

Note - I have not used csv file but assumed that csv is read and converted to an array

Aditya Bhave
  • 998
  • 1
  • 5
  • 10
  • I still can not get my code to work even with changing attr to html – beginnerDeveloper Aug 21 '18 at 18:57
  • Ok. I got it working. Find it here - https://jsfiddle.net/o2gxgz9r/65690/ (I have commented the code that reads csv file from server. Uncomment it once you have file on server) Changes required: 1. Host file and html on the server (IIS or any other server) 2. Put the code inside document.ready function – Aditya Bhave Aug 22 '18 at 15:28