html input fileupload returning null

6.2k views Asked by At

I am trying to make a demo involving an html input file uploader and ajax, but I can't even get my script to getElementById.

I keep receiving an TypeError: form is null.

Here is my html and script:

<form id="file-form" action="handler.php" enctype="multipart/form-data" method="POST">
  <input type="file" id="file-select" name="photos[]" multiple/>
  <button type="submit" id="upload-button">Upload</button>
</form>

<script type="text/javascript">
    var form = document.getElementById("file-form");
    var fileSelect = document.getElementById("file-select");
    var uploadButton = document.getElementById("upload-button");

form.onsubmit = function (event) {
    event.preventDefault();

    // Update button text.
    uploadButton.innerHTML = 'Uploading...';
}
</script>

Note that 'fileSelect' and 'uploadButton' are receiving their elements and are not null.

For some reason form is not able to getElement.

I've seen several similar questions, but it seems like I am doing the right thing. Let me know if you have any suggestions.

Thanks in advance.

EDIT: I should add that this demo is in an ASP .ascx User Control Form. kami-sama's Code Snippet worked perfectly fine, but it will not do the same in my solution.

I log the 'form' variable after getElementById and it returns null and does not proceed past the form.onsubmit = function(event) line.

2

There are 2 answers

0
cs04iz1 On

You should declare that your form will be handling uploaded files by adding the enctype="multipart/form-data"

w3 w3schools

4
Vladimir Atamanenko On

I just added closing bracket to your code and it's working just fine in StackOverflow code snippet and in Firefox with html file.

var form = document.getElementById("file-form");
var fileSelect = document.getElementById("file-select");
var uploadButton = document.getElementById("upload-button");

form.onsubmit = function (event) {
    event.preventDefault();

    // Update button text.
    uploadButton.innerHTML = 'Uploading...';
}
<form id="file-form" action="handler.php" method="POST">
  <input type="file" id="file-select" name="photos[]" multiple/>
  <button type="submit" id="upload-button">Upload</button>
</form>