0

Ok I can't seem to figure out why this variable is coming back undefined in my alert box. What am I missing here?

<html>
<script src="xslt.js"></script>
<script>
var file;
var objecturl;
var files;
var filename="filename goes here";
function handleFileSelect(evt) {
    files = evt.target.files; // FileList object
    file = files[0];
    filename = file.name;
}
function submit() {
alert(filename);
}
document.getElementById('files').addEventListener('change', handleFileSelect, false);
</script>
Select your XML/CCD File(s):<input type="file" id="files" name="files[]" multiple />
<input id="clickMe" type="button" value="View CCD" onclick="submit();" />
<div id="transformResult"></div>
</html>
6
  • It doesn't, it comes back "filename goes here" Commented May 21, 2014 at 15:58
  • Weird, for me it comes back as undefined. Commented May 21, 2014 at 15:58
  • @Kyle what browser are you using? Commented May 21, 2014 at 15:58
  • If I fix the error with the script appearing before the input it tries to modify, then it comes back with the file name of the file I picked, so I still can't reproduce the problem. Commented May 21, 2014 at 15:59
  • Chrome browser, which has worked in the past with other code I've written similar to this. Commented May 21, 2014 at 16:00

2 Answers 2

1

Try this:

<script>
var file;
var objecturl;
var files;
var filename="filename goes here";
function handleFileSelect(evt) {
    files = evt.target.files; // FileList object
    file = files[0];
    filename = file.name;
}
function submit() {
alert(filename);
}
</script>

Select your XML/CCD File(s):<input type="file" id="files" name="files[]" multiple />
<input id="clickMe" type="button" value="View CCD" onclick="submit();" />
<div id="transformResult"></div>

<script>
document.getElementById('files').addEventListener('change', handleFileSelect, false);
</script>

Notice I moved the addEventListener to a script that runs after the elements are loaded in the DOM.

Sign up to request clarification or add additional context in comments.

Comments

0

You have to wait for the input field to be in the dom before calling getElementById, hence filename is not set.

4 Comments

While that is an error in the code in the question, it doesn't explain the result that is described there.
Alright, so what would be the best way to rearrange this so that it is loaded in the correct order.
you should put it in a load handler.
Move the script element to after the input element.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.