Is there a way to automatically remove the upload button after the file has been successfully uploaded?

I'm currently using blueimp and jquery UI to handle file uploads.

My goal is to dynamically hide a specific button once a file is uploaded, and then display it again if the photo is removed. How can I achieve this functionality?

https://i.stack.imgur.com/Iab9i.png

Below is the HTML code snippet:

<form class="fileupload" action="${pageContext.request.contextPath}/someUrl"
      method="POST" enctype="multipart/form-data">
    <noscript><input type="hidden" name="redirect" value="https://www.somedomain.com"/></noscript>
    <input type="hidden" name="type" value="image1">

    <div class="row fileupload-buttonbar">
        <div class="col-lg-7">
            <span class="btn btn-info fileinput-button"><i class="fa fa-plus"></i> Add one photo...
                <input type="file" name="image" accept="image/png, image/jpeg">
            </span>
            <span class="fileupload-process"></span>
        </div>
        <div class="col-lg-5 fileupload-progress fade">
            <div class="progress progress-striped active" role="progressbar"
                 aria-valuemin="0"
                 aria-valuemax="100">
                <div class="progress-bar progress-bar-success" style="width:0;"></div>
            </div>
            <div class="progress-extended">&nbsp;</div>
        </div>
    </div>
    <table role="presentation" class="table table-striped">
        <tbody class="files"></tbody>
    </table>
</form>

The X-TMPL implementation:

<!-- File upload template for displaying available files -->
<script id="template-upload" type="text/x-tmpl">
{% for (var i=0, file; file=o.files[i]; i++) { %}
    <tr class="template-upload fade">
        <td>
            <span class="preview"></span>
        </td>
        <td>
            <p class="name">{%=file.name%}</p>
            <strong class="error text-danger"></strong>
        </td>
        <td>
            <p class="size">Processing...</p>
            <div class="progress progress-striped active" role="progressbar" aria-valuemin="0" aria-valuemax="100" aria-valuenow="0"><div class="progress-bar progress-bar-success" style="width:0%;"></div></div>
        </td>
        <td>
            {% if (!i && !o.options.autoUpload) { %}
                <button class="btn btn-info start" disabled>
                    <span>Start</span>
                    <i class="fa fa-caret-right"></i>
                </button>
            {% } %}
            {% if (!i) { %}
                <button class="btn btn-warning cancel">
                    <i class="fa fa-trash-o"></i>
                    <span>Remove Photo</span>
                </button>
            {% } %}
        </td>
    </tr>
{% } %}
</script>
<!-- Template for displaying downloaded files -->
<script id="template-download" type="text/x-tmpl">
{% for (var i=0, file; file=o.files[i]; i++) { %}
    <tr class="template-download fade">
        <td>
            <span class="preview">
                {% if (file.thumbnailUrl) { %}
                    <a href="{%=file.url%}" title="{%=file.name%}" download="{%=file.name%}" data-gallery><img src="{%=file.thumbnailUrl%}"></a>
                {% } else { %}
                    <img src="{%=file.thumbnail_url%}">
                {% } %}
            </span>
        </td>
        <td>
            <p class="name">
                {% if (file.url) { %}
                    <a href="{%=file.url%}" title="{%=file.name%}" download="{%=file.name%}" {%=file.thumbnailUrl?'data-gallery':''%}>{%=file.name%}</a>
                {% } else { %}
                    <span>{%=file.name%}</span>
                {% } %}
            </p>
            {% if (file.error) { %}
                <div><span class="text-danger"><i class="fa fa-exclamation-circle"></i> Error</span> {%=file.error%}</div>
            {% } %}
        </td>
        <td>
            <span class="size">{%=o.formatFileSize(file.size)%}</span>
        </td>
        <td>
            {% if (file.deleteUrl) { %}
                <button class="btn btn-danger delete" data-type="{%=file.deleteType%}" data-url="{%=file.deleteUrl%}"{% if (file.deleteWithCredentials) { %} data-xhr-fields='{"withCredentials":true}'{% } %}>
                    <i class="fa fa-trash-o"></i>
                    <span>Remove Photo</span>
                </button>
                <input type="checkbox" name="delete" value="1" class="toggle">
            {% } else { %}
                <button class="btn btn-warning cancel">
                    <i class="fa fa-trash-o"></i>
                    <span>Remove Photo</span>
                </button>
            {% } %}
        </td>
    </tr>
{% } %}
</script>

A similar thread on Stack Overflow that I came across is not directly related to my query, here.

Update:

I attempted the callback solution provided by @ZakariaAcharki:

console.log('start')
$('input[name="image"]')
    .bind('fileuploadcompleted', function (e, data) {
        console.log('hiding')
        $('.fileinput-button').hide();
    })
    .bind('fileuploaddestroyed', function (e, data) {
        console.log('showing')
        $('.fileinput-button').show();
    });
console.log('ended')

The output indicates: 'start' and 'ended'. I'm unsure why the callbacks are not triggering as expected.

Update 2: While hiding works with this solution, showing does not.

$('.fileupload')
    .bind('fileuploaddone', function (e, data) {
        console.log('hide');
        $('.fileinput-button').hide();
    })
    .bind('fileuploaddestroy', function (e, data) { //also tried with 'fileuploaddestroyed'
        console.log('show');
        $('.fileinput-button').show();
    });

In addition to unchanged tmpl.min.js and jQuery file upload/UI files, here is the JavaScript code:

/*
 * jQuery File Upload Plugin JS Example 8.9.1
 * https://github.com/blueimp/jQuery-File-Upload
 *
 * Copyright 2010, Sebastian Tschan
 * https://blueimp.net
 *
 * Licensed under the MIT license:
 * http://www.opensource.org/licenses/MIT
 */

/* global $, window */

$(function () {
    'use strict';

    var uploadPaths = ["fileA", "fileB", "fileC", "fileCA", "fileCB", "fileCC"];

    // Initialize the jQuery File Upload widget:
    $('.fileupload').each(function (index) {
        $(this).fileupload({
            dropZone: $(this),
            acceptFileTypes: /(\.|\/)(gif|jpe?g|png|doc|docx|pdf|ppt|pptx)$/i,                 
            maxFileSize: 10000000, // 10 MB

            // Error and info messages:
            messages: {
                acceptFileTypes: 'Sorry, this file type is not allowed. Please ensure the file extension is one of .gif, .jpg, .jpeg, .png, .doc, .docx, .pdf, .ppt, or .pptx.',  
                maxFileSize: 'Please make sure your file size is under 10 MB.'
            }
        });

        // Load existing files:
        $(this).addClass('fileupload-processing');
        $.ajax({
            url: '/' + uploadPaths[index],
            context: $(this)
        }).done(function (data) {
            $(this).fileupload('option', 'done').call(this, $.Event('done'), {result: {files: data.files}});
            $(this).removeClass('fileupload-processing');
        });
    });

    // Enable iframe cross-domain access via redirect option:
    $('#fileupload').fileupload(
        'option',
        'redirect',
        window.location.href.replace(
            /\/[^\/]*$/,
            '/cors/result.html?%s'
        )
    );
});

Answer №1

Have you checked out the events fileuploadcompleted and fileuploaddestroyed :

$('input[name="image"]')
    .bind('fileuploadcompleted', function (e, data) {
         $('.fileinput-button').hide();
    })
    .bind('fileuploaddestroyed', function (e, data) {
         $('.fileinput-button').show();
   });

I hope this information is useful to you.

Answer №2

Our developer has come up with a clever solution using CSS to toggle the visibility of a button based on certain events.

Within the block of code starting with:

$('.fileupload').each(function (index)
, specific bindings are set:

$(this).bind('fileuploaddone', function (e, data){
    var form = $(this).closest("form");
    var uploadButton = form.find(".btn.btn-info.fileinput-button");        
    uploadButton.css("visibility", "hidden");
});

// To load existing files:
if (typeof allFiles[index] !== 'undefined')      
   if (typeof allFiles[index] !== 'undefined'){
      $(this).fileupload('option', 'done').call(this, $.Event('done'), {result: {files: allFiles[index].files}});
      var form = $(this).closest("form");
      var uploadButton = form.find(".btn.btn-info.fileinput-button");
      uploadButton.css("visibility", "hidden");
   }
  });                 
});

Later on, the button is made visible again within a function called markImageAsDeleted:

var uploadButton = form.find(".btn.btn-info.fileinput-button");
uploadButton.css("visibility", "visible");

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

Pop-up windows, the modern day digital version of fortune cookies

Expressing my requirement might be a bit challenging, but I will do my best. My goal is to create a web application using ASP.Net with C#. This project calls for functionality similar to the Windows popup: When a user clicks on the favorite button in IE- ...

After zooming in on the canvas and panning, I encountered a problem where I was unable to drag objects within the canvas. Instead, the canvas continued to pan as I tried to move the objects

1) I have the ability to pan the canvas and drag images without scaling or zooming. 2) When scaling or zooming, I can still drag images within the canvas. 3) However, if I try to pan the canvas after zooming and then attempt to drag images, only the canv ...

Adjusting the text color based on the dynamically set background color

If I have a calendar where each entry has a unique background color assigned to it (one color per user), including both light and dark colors that users can choose from, how can I set the text color to match the background style? Where should I begin wit ...

problem encountered when transferring data using ajax

I'm struggling with figuring out how to use an ajax function My goal is to send PHP variables via ajax to another page when a user clicks on a link Javascript function sendData(a, b, c, d) { $.ajax({ url: "page.php", typ ...

Customize your popover content with Bootstrap settings

I've been on a quest to dynamically update the content of a Bootstrap popover using JavaScript, but unfortunately, the methods I've tried so far haven't worked out as expected : <!--object with the popover--> <input id="popoverlist ...

Disable the click event using jQuery

$("button").click(function (){ $("<button>Start</button>).appendTo('main'); }); The code above introduces a functionality where clicking a button generates another button dynamically. However, each subsequent click kee ...

What is a more efficient method for switching between edit mode and view mode in ng-grid?

Up until now, I've only managed to switch the edit mode in ng-grid by using separate templates and showing the correct template based on user input. For example: Plunker (resize a column and then switch to another mode) This poses a problem because ...

Prevent Click Event in JQuery

I have a requirement to disable all click events on my webpage. However, even after using the appropriate code to prevent these events from firing, some of them are still getting called. Let me explain with an example. <div id='parent'> ...

Submitting a Yii 2 form automatically when it loads

Pjax::begin(); $form = ActiveForm::begin(); echo $form->field($model, 'testdata', [ 'inputOptions' => [ 'class' => 'form-control input-xsmall input-inline' ], ...

jQuery replacing spaces in id names

I'm encountering an issue with the following HTML and jQuery code. The problem seems to be related to the space in the ID name. HTML <span id="plus one">Plus One</span> jQuery $("#plus one").hide(); Since I'm unable to change the ...

Clicking on the images will display full page versions

Apologies for not making an attempt just yet, but I'm struggling to locate what I need. Here's the menu structure in question: <div class="overlay-navigation"> <nav role="navigation"> <ul class="test"> & ...

Interactive Show Map with Autocompletion Feature

I attempted to implement autocompletion for my application and integrate it with Google Maps, but I'm encountering issues. The code for autocompletion is located in a separate JavaScript file called autocomplete.js. Since I already have a Google Map ...

Display or conceal numerous WTForm labels

Is there a more efficient way to hide/show multiple wtform labels? Currently, I am achieving this with the following code: HTML: {{ render_field(var_1, class = "class_1") }} {{ render_field(var_2, class = "class_1") }} {{ render_field(var_3, class = " ...

To ascertain whether the mouse is still lingering over the menu

I have a condensed menu construction that unfortunately cannot be changed in HTML, only CSS and JS modifications are possible! $('span').on("hover", handleHover('span')); function handleHover(e) { $(e).on({ mouse ...

What is the best way to populate a table with form text fields using jQuery?

I have a scenario where I need to toggle between two forms. The initial form #form1 includes input fields for month and year, along with a search button. The secondary form #form2 consists of a table that needs to be populated based on the month and year s ...

Align the text to the center beneath the image using Jquery's append function

I am looking to showcase a collection of fruits and vegetables through images, with the names displayed centered underneath each image. Additionally, I want to implement jQuery append functionality so that the names only appear when a specific button is cl ...

Avoiding multiple ajax requests due to multiple clicks

I have a blog on WordPress that has a jQuery code allowing users to click a bookmark link to save the post as a bookmark. Each post displays a total bookmark counter in this format: "Bookmarked (5)". The issue is that when a user clicks multiple times on t ...

What is the best way to capture user input using an onClick event in JavaScript and then display it on the screen?

I'm in the process of upgrading a table, and while most of it is working fine, there is one function that's giving me trouble. I want this function to return an input with an inline onClick event. The actual return value is displaying correctly, ...

Sliding Image Menu using jQuery

I am struggling with creating a menu using jquery mouseenter / mouseout effects. My goal is to have a small icon displayed that expands to the left and reveals the menu link when a user hovers over it. The issue I am facing is that the effect only works w ...

Discover the power of the "Load More" feature with Ajax Button on

After browsing through the previous questions and experimenting with various techniques, I've come close to a solution but still can't get it to work. The closest example I found is on Stack Overflow: How to implement pagination on a custom WP_Qu ...