I am encountering an issue with multiple forms on my website. Each form accepts a file upload and then displays the upload status in a specific element. However, when updating one form, the status is displayed on a different form, causing confusion for users.
Is there a way to ensure that each form updates its status independently based on which form is being updated?
Below is the code I am using:
<script>
function _(el) {
return document.getElementById(el);
}
function uploadFile(element) {
var file = _("file1").files[0];
alert(file.name+" | "+file.size+" | "+file.type);
var formdata = new FormData();
formdata.append("file1", file);
var ajax = new XMLHttpRequest();
var uploadValue = element.getAttribute("data-uploadValue");
ajax.upload.addEventListener("progress", progressHandler, false);
ajax.addEventListener("load", completeHandler, false);
ajax.addEventListener("error", errorHandler, false);
ajax.addEventListener("abort", abortHandler, false);
ajax.open("POST", "/upload/" + uploadValue); //
ajax.send(formdata);
}
function progressHandler(event) {
_("loaded_n_total").innerHTML = "Uploaded " + event.loaded + " bytes of " + event.total;
var percent = (event.loaded / event.total) * 100;
_("progressBar").value = Math.round(percent);
_("status").innerHTML = Math.round(percent) + "% uploaded... please wait";
}
function completeHandler(event) {
_("status").innerHTML = event.target.responseText;
_("progressBar").value = 0; //wil clear progress bar after successful upload
}
function errorHandler(event) {
_("status").innerHTML = "Upload Failed";
}
function abortHandler(event) {
_("status").innerHTML = "Upload Aborted";
}
</script>
<form id="upload_form" enctype="multipart/form-data" method="post">
<div class="file has-name is-fullwidth is-info">
<label class="file-label">
<input class="file-input" type="file" name="file1" id="file1" data-uploadValue="{{ item[0] }}" onchange="uploadFile(this)"><br>
<span class="file-cta">
<span class="file-icon">
<i class="fa fa-upload"></i>
</span>
<span class="file-label">
Choose a file…
</span>
</span>
<span class="file-name">
<div style="color:red;" id="status"></div>
Supported file types: .png, .jpg, .jpeg and .gif
</span>
</label>
<div style="display:none">
<p id="loaded_n_total"></p>
<progress id="progressBar" class="progress" value="0" max="100" style="width:300px;"></progress></div>
</div>
</form>
Update 1: I have modified the JavaScript code to be more reliable.
Update 2: To address the issue, I incorporated unique identifiers for each form within the JavaScript loop corresponding to each form. This adjustment did not resolve the problem as intended.
Update 3: A potential conflict arises from having additional forms preceding the upload form, specifically containing a text area. While the provided solution works without these extra forms, it encounters complications when they are present.