I’m attempting to read in a file using this form in my :
<form name="UploadForm" method="post">
<input type="hidden" name="MAX_FILE_SIZE" value="100000" />
Choose a CSV file to upload: <input name="upload_file" type="file" /><br />
<input type="submit" value="Upload" onClick="uploadFile()" />
</form>
But when I go to read the value in this function within I receive a “cannon find “elements” of null error:
function uploadFile() {
var file = document.getElementById('UploadForm').elements['upload_file'].value;
var allTextLines = file.split(/\r\n|\n/);
var headers = allTextLines[0].split(',');
var lines = [];
for (var i=1; i<allTextLines.length; i++) {
var data = allTextLines[i].split(',');
if (data.length == headers.length) {
var tarr = [];
for (var j=0; j<headers.length; j++) {
tarr.push(headers[j]+":"+data[j]);
}
lines.push(tarr);
}
}
alert(lines);
};
Does anybody have any ideas as to what I’m doing wrong?
getElementByIdreturns the element with the specified id, but the form doesn’t have anidat all. You are using the obsoletenameattribute (which was superseded byidwhen HTML 4 was released in 1998).Change it to:
(N.B.
nameis not obsolete on form controls, such asinputandselect)Note that your event handler isn’t cancelling the default behaviour of the submit button. So as well as running the JS, you will immediately submit the form, leave the page, and cancel the JS (if it does anything asynchronous, which the name suggests it will be).
If you are going to use intrinsic event attributes, then you need to
return falseif the JavaScript succeeds.I recommend giving them up in favour of
addEventListenerthough.