Apologies in advance as I’m very new to javascript. Essentially, I cobbled together 2 scripts and which I’m trying to get to work. I know that javascript can’t normally access local files but with the File object it may be possible?
In the code below, if my selected file is a CSV, how can I pass it to the next function $.get('data.csv', function(data) so 'data.csv' is actually the file selected?
<html>
<script type="text/javascript">
document.getElementById('file').addEventListener('change', handleFileSelection, false);
function handleFileSelection(evt) {
console.log(evt);
var f = evt.target.files[0];
}
$(document).ready(function() {
$.get('data.csv', function(data) {
// Split the lines
var lines = data.split('\n');
//more code
});
});
</script>
<body>
<input type="file" id="file" name="file" />
<output id="list"></output>
</body>
</html>
The first problem what I see here is that you are trying to add event listener earlier than the actual element is created (as RobG said).
And the second problem that I can mention is that you’re trying to use
$.getto parse that local CSV file. If you are using jQuery, then$.getmakes a GET asynchronous request to some URL and it is not what you need. You have to investigate FileReader object. I am not familiar with it, so I can’t bring an example of working code, but you can look for some examples here.