Christhemist
Christhemist

Reputation: 19

Why is form submit happening before file upload is finished?

I have created a button to replace the input file type, but when I programmatically click the input file type it submits the form before the file is uploaded. I need the file upload to finish before it submits the form.

HTML:

<form action="" method="post" enctype="multipart/form-data">
  <button class="btn btn-space btn-primary" id="uploadFileButton">Upload File</button>
  <input type="file" name="fileToUpload" id="fileToUpload" accept=".xls, .xlsx, .csv, .txt">
</form>

JavaScript:

document.getElementById("uploadFileButton").onclick = function() {
  document.getElementById("inputFileUpload").click();
};

document.getElementById("inputFileUpload").onchange = function() {
  document.getElementById("uploadForm").submit();
};

Upvotes: 1

Views: 282

Answers (2)

charlietfl
charlietfl

Reputation: 171669

The default type for <button> is "submit"

Set it's type to 'button' to prevent it submitting the form

<button type="button" class="btn btn-space btn-primary" id="uploadFileButton">Upload File</button>

Upvotes: 1

Christhemist
Christhemist

Reputation: 19

The issue was the replacement button "uploadFileButton" was inside the form tags. Placing it outside the form fixed the issue.

Upvotes: 0

Related Questions