I am trying to automatically prompt a user to upload a CSV file and then I plan to access the data within, but I am unable to do this. What am I doing wrong? input.name is always undefined and viewing the whole object doesn't provide any relevant details.
The source of this query primarily came from the answer to this question Open file dialog box in JavaScript. I am trying to achieve this purely in javascript, not HTML.
$(document).ready(function() {
var input = $(document.createElement('input'));
input.attr("type", "file");
input.on('change',function(){
alert(JSON.stringify(input.name, null, 4));
alert(JSON.stringify(input, null, 4));
});
input.trigger('click');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
input is the return value of $(). It is a jQuery object not a DOM object. To access the name property of the underlying DOM object, use the prop method.
input.prop('name')
I finally got it working. Here is the solution
$(document).ready(function() {
var input = $(document.createElement('input'));
input.attr("type", "file");
input.on('change', function() {
var csvFile = input[0].files[0];
var ext = csvFile.name.split(".").pop().toLowerCase();
if (ext != "csv") {
alert('upload csv');
return false;
}
if (csvFile != undefined) {
reader = new FileReader();
reader.onload = function(e) {
var data = $.csv.toObjects(e.target.result);
alert(JSON.stringify(data, null, 4));
$.each(data, function(index, val) {
//do something with each row of data val.ColumnName
});
}
reader.readAsText(csvFile);
}
});
input.trigger('click');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-csv/1.0.21/jquery.csv.js"></script>