Tips for universalizing the code of a file upload web form to accommodate various forms with distinct id attributes

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?

Answer №1

Attempt

//Include data-progress and data-message attributes with their respective ids as values
<form id="uploadFileForm" method="post" action="upload.php" enctype="multipart/form-data" data-progress="#progress" data-message="#message">
    <input type="file" size="60" name="fileToUpload" />
    <input type="submit" value="Upload" />
</form>
<div id="progress" class="progress">
    <div id="bar" class="bar"></div>
    <div id="percent" class="percent">0%</div>
</div>
<br />
<div id="message" class="message"></div>

next

$(document).ready(function () {
    function ajaxSubmit(form) {
        var $form = $(form),
            $progress = $($form.data('progress')),
            $message = $($form.data('message')),
            $bar = $progress.find(".bar"),
            $percent = $progress.find(".percent");
        var options = {
            beforeSend: function () {
                $progress.show();
                //clear all fields
                $bar.width('0%');
                $percent.html("");
                $message.html("0%");
            },
            uploadProgress: function (event, position, total, percentComplete) {
                $bar.width(percentComplete + '%');
                $percent.html(percentComplete + '%');
            },
            success: function () {
                $bar.width('100%');
                $progress.find(".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>");
            }

        };
    }
    ajaxSubmit($("#uploadFileForm"));
    ajaxSubmit($("#uploadFileForm1"));
    ajaxSubmit($("#uploadFileForm2"));
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Finding the exact x and y coordinates of an object within the camera's frame

I'm currently working on figuring out the exact location (x, y, z coordinates) of an object (a BoxGeometry) in the world in reference to the screen (frustum) rather than the world itself. While the frustum.intersectsObject(…) method provides a Boole ...

Tips for implementing a checkbox (with tick/untick functionality) as a replacement for a plus/minus toggle using HTML

Is it possible to use checkboxes instead of plus and minus signs for expanding and collapsing sections? Can the plus and minus symbols be incorporated into the checkbox itself, so that clicking on the checkbox toggles between plus and minus states? Any hel ...

Ensuring all fetch requests are completed successfully before dispatching an action in React-Redux

I'm currently developing a React application and utilizing Redux to manage the state. Here is a snippet of the code: category-arrows.component.jsx: import React, { Component } from 'react'; import { connect } from 'react-redux'; i ...

Converting a jQuery function into AngularJS: A step-by-step guide

I'm completely new to AngularJs and I recently created a slider function using jQuery. Now, my goal is to convert this function into Angular. Below is the code snippet that I have: <div class="slide-container"> <div class="slide-s ...

Stacking sheets of hole-punched paper on top of one another, create a visually captivating

I am in search of a way to create those distinctive black dots with papers displayed here: body { background: linear-gradient(#ccc, #fff); font: 14px sans-serif; padding: 20px; } .letter { background: #fff; box-shadow: 0 0 10px rgba ...

Increase the character count when two spans contain data

I am currently working with the code provided below. The user interface allows users to choose either a single date or a range of dates. These dates are displayed within span tags, with a "-" symbol intended to be shown if there is a valid toDate. However, ...

Even after dynamically removing the class from the element, the Click event can still be detected

My buttons have a design like this: <a class="h-modal-btn branch-modal-btn"> Buy Now </a> The issue arises when I need to remove certain classes and add attributes to these buttons based on the query string in the URL. Skipping ahead ...

The Page is Not Able to Scroll

Occasionally, my app stops allowing scrolling of the entire page length. Everything will be working fine for a while, but then out of nowhere, the page suddenly becomes un-scrollable and you can only interact with the section currently visible on the scree ...

Adjust the dimensions of an SVG element using CSS within an li element's ::before pseudo-element

I'm working on a list where SVGs are loaded as list items. How can I adjust the height and width of the ::before pseudo-element to be 30px x 30px? Setting the height and width directly didn't work for me. Can someone assist with this? <div cl ...

Switch between GeoJSON layers by using an HTML button within Mapbox GL JS, instead of relying on traditional links

I am currently developing a web map that requires toggling two GeoJSON layers on and off. In the past, I used Mapbox JS to accomplish this task by adding and removing layers with a custom HTML button click. However, I am facing some challenges in achieving ...

Adjust the tooltip image alignment to be offset from the cursor and appear at the bottom of the page

After creating a code snippet for image tooltips on text hover, I encountered an issue on my website where the bottom of the page expanded to accommodate the images. Is there a simple way to align the cursor at the bottom of the image when scrolling to the ...

Tips for changing the size of a column in Kendo Grid

Here is the grid display setup: When a column name is clicked, an arrow is added for sorting in the column header. To accommodate this feature, I need to resize my column width. Please note: The column names and data are added dynamically from the databa ...

Distinguishing the Mouse Wheel Event

Take a look at this code snippet: <script type="text/javascript"> var scrollFunc = function(e) { var direct = 0; e = e || window.event; if(e.wheelDelta) {//IE/Opera/Chrome userMouse(e.wheelDelta); } else if(e.detail) {//Fire ...

Different XML sources can be used for every request with jQuery Ajax

Is there a way to alternate between two XML data sources on each page load? Currently, I am using an ajax request to retrieve data from one source: $(document).ready(function() { $.ajax({ type: "GET", url: "sou ...

Combining ExtJS Paging with Dropdown Selection

Having an issue with a combo box created using the ExtJS framework. The pagination feature is not working correctly. Can anyone provide assistance with this? var store = new Ext.data.ArrayStore({ fields: ['id'], pageSize:1, data : ...

Validation is key! jQuery form validation triggers a popup notification upon successful submission

I am currently working on implementing a popup that appears when the user clicks "Submit" and all inputs are valid. Here is my current progress: $(document).ready(function() { $("#aForm").validate({ debug: false, errorPlacement: functi ...

What is the reason behind shadow dom concealing HTML elements when viewed in inspect mode?

https://i.stack.imgur.com/UZM7f.png Monday.com has implemented Shadow Dom to protect its source code. How can I work around this limitation? ...

What is the method for displaying data from a JSON file that is associated with the wallet address of the authenticated user in next.js?

I am currently working on a claim page using next.js, where logged in Metamask addresses can perform the following tasks: Access data from a local .json file to check eligibility for claiming an item and display the claim page. Submitting a form to update ...

The node module.exports in promise function may result in an undefined return value

When attempting to log the Promise in routes.js, it returns as undefined. However, if logged in queries.js, it works fine. What changes should be made to the promise in order to properly return a response to routes.js? In queries.js: const rsClient = req ...

Utilize Three.js to Add Depth to 2D Images with Extrusion

After searching online, I have been unable to find a method to extrude a colored image in Three.js. My goal is to create a design similar to a Minecraft item where the image is used to generate an extruded geometry. An example of what I'm trying to ac ...