Reputation: 19
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
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
Reputation: 19
The issue was the replacement button "uploadFileButton" was inside the form tags. Placing it outside the form fixed the issue.
Upvotes: 0