Presently, I have a web form dedicated to uploading a single file using jquery. This elegant solution provides users with a progress bar and a message upon the successful completion of the upload process:
<form id="uploadFileForm" method="post" action="upload.php" enctype="multipart/form-data">
<input type="file" size="60" name="fileToUpload" />
<input type="submit" value="Upload">
</form>
<div id="progress">
<div id="bar"></div>
<div id="percent">0%</div >
</div>
<br />
<div id="message"></div>
In the head section of the webpage, I have included the necessary javascript code to detect the upload form by its unique id. Additionally, there is CSS styling defined to enhance the appearance of the progress bar and message divs:
<script>
$(document).ready(function()
{
var options = {
beforeSend: function()
{
$("#progress").show();
//clear everything
$("#bar").width(\'0%\');
$("#message").html("");
$("#percent").html("0%");
},
uploadProgress: function(event, position, total, percentComplete)
{
$("#bar").width(percentComplete+\'%\');
$("#percent").html(percentComplete+\'%\');
},
success: function()
{
$("#bar").width(\'100%\');
$("#percent").html(\'100%\');
},
complete: function(response)
{
$("#message").html("<font color=\'#85a129\'>"+response.responseText+"</font>");
},
error: function()
{
$("#message").html("<font color=\'#CC3300\'> ERROR: unable to upload files</font>");
}
};
$("#uploadFileForm").ajaxForm(options);
});
</script>
<style>
#progress { position:relative; width:400px; border: 1px solid #ddd; padding: 1px; border-radius: 3px; }
#bar { background-color: #85a129; width:0%; height:20px; border-radius: 3px; }
#percent { position:absolute; display:inline-block; top:3px; left:48%; }
</style>
The current setup is functional and satisfactory. However, expanding this functionality to include multiple forms for different files on the same page requires redundant duplication of code. How can I adapt my javascript to dynamically handle all upload forms, progress bars, and messages?
Furthermore, is it possible to create a single CSS style that will apply uniformly to all progress bars regardless of their individual ids?