How can a Spinner be incorporated into a Button within a Modal while running in the background?

I'm attempting a rather simple task, but I'm encountering difficulties.

The issue I'm facing involves a modal that prompts the user for confirmation. Once the user clicks "confirm," a URL is fetched, triggering a background process. During this period, a loading spinner should be displayed on the button. I've experimented with various onclick events for the button. While the console shows that the function is being activated, the button itself fails to change upon clicking "confirm."

What is the correct method to update the button in the modal during the loading process? There's no need to revert the button's state, as the user will be redirected to a different page once the process is complete.

My setup involves Bootstrap 4 and Django.

This is the HTML for the Modal:

                      <!-- Modal -->
                      <div class="modal fade" id="Modal{{ forloop.counter }}" tabindex="-1" role="dialog" aria-labelledby="ModalLabel{{ forloop.counter }}" aria-hidden="true">
                        <div class="modal-dialog" role="document">
                          <div class="modal-content">
                            <div class="modal-header">
                              <h5 class="modal-title" id="exampleModalLabel">Are you sure you want to delete this Application?</h5>
                              <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                <span aria-hidden="true">&times;</span>
                              </button>
                            </div>
                            <div class="modal-body">
                              <p>
                               <br>
                              <b>Name:</b> {{item.Name}} <br>
                              <b>Version:</b> {{item.Version}} <br>
                              <b>Publisher</b> : {{item.Publisher}} <br>
                              <b>Language:</b> {{item.Language}} <br>
                              <b>Command Line:</b> {{item.CommandLine}} <br>
                              <br>
                              Depending on the application size, this can take a while.<br>
                              Please wait, till this windows closes automatically
                            </p>
                            
                            </div>
                            <div class="modal-footer">
                              
                              <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                              <a href="{% url 'delete_application' share.share.Name share.share.Path item.Name %}"class="btn btn-danger" id="btn-delete">Confirm</a>
                              
                            </div>
                          </div>
                        </div>
                      </div>

EDIT 1

To alter the button content, I implemented the following:

$(document).ready(function(){
 $('#btn-delete').on('click', function () {
  var text=$('#btn-delete').text();
  if(text === "Confirm"){
    $(this).html('Loading');
 }
});
});

However, this only works when the button is not within the Popup Modal. The button within the Modal remains unaffected by the function.

Answer №1

After struggling with the issue for some time, I managed to find a workaround that did the trick, albeit in a rather messy way.

The root of the problem lay in the need to modify the HTML content of the modals, as the button was an integral part of it.

To resolve the issue, I took the following steps:

Firstly, I assigned an ID to my btn-delete button. Given that I was working with Django, I opted to include a unique identifier related to the modal in the button's ID. Additionally, I added an onclick function to pass the button's ID into a handler function.

<a href="{% url 'delete_application' share.share.Name share.share.Path item.Name %}" class="btn btn-danger" id="btn-delete{{ forloop.counter }}" onclick="showLoading(this.id)">Confirm</a>

With this setup, I then utilized the following JavaScript code to make the necessary changes:

function showLoading(id){
    // Extract the modal and button IDs by parsing the button's ID
    id = id.replace(/^[^\d]+/, "");
    // Retrieve the specific modal
    var mymodal = $('#Modal' + id);
    // Locate the designated delete button and update its HTML content
    mymodal.find('#btn-delete' + id).html('Confirm <span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span>');
}

Although the solution may not be elegant, it successfully resolved the issue in my case.

Answer №2

Consider two states of a button and write two functions:

Function 1: Make the button disabled and activate the loading state.

Function 2: Make the button enabled and remove the loading state.

In the functions, perform the desired actions. I recommend placing a spinning span inside the button and toggling the appearance class. Toggle the disabled property based on functionality.

Once the functions are complete, before starting a time-consuming operation, make the button unclickable and in a loading state. After the operation is finished, return the button to its normal state.

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

What is the best way to incorporate CSS into an Angular 4 project?

I'm struggling to figure out how to import CSS into my app component. All the information I find on Google seems to lead me in different directions... Within my component, I have defined: @Component({ styleUrls: ['../css/bootstrap.min.css&ap ...

Comment sections that refresh automatically after being posted

I am determined to provide a clear explanation. Despite having some code, I am uncertain about how to make it clone comments and add new ones with user inputted text. Below is the snippet of code I am struggling with: <!DOCTYPE html> <!-- this i ...

Using Ajax/jQuery in combination with Mongodb

My experience with Ajax/jQuery is fairly new. I am currently working on creating a sample HTML page using Ajax/jQuery to retrieve all customers and search for a customer by ID. Each customer has three variables: ID, firstName, and lastName. I am looking t ...

Transferring information from MySQL to Vue.js data attribute

I have retrieved some data from MySQL and I am looking to integrate it into a vue.js data property for seamless iteration using v-for. What is the ideal format to use (JSON or array) and how can I ensure that the data is properly accessible in vue.js? &l ...

What is the reason for the checkboxes in vuejs not being rendered with the checked attribute set

When working on an edit form, I encountered a situation where I had multiple options to choose from. These options were fetched via ajax using axios and assigned to the variable permisos in the component. Later, these options are rendered through a v-for l ...

Strange results appearing on my node.js server - removing object

When I run node.js in the terminal, I get this output: node server.js { hand: [ [ [Object], [Object] ], [ [Object], [Object] ], [ [Object], [Object] ], [ [Object], [Object] ] ], deck: [ { suit: 'c', rank: 'a' ...

Unresponsive jQuery Ajax JSON Request

I am working with a basic Ajax function: insertInto = function(){ console.log("Hello "); var power = $("#power").val(); var vehicle = $("#vehicle").val(); var sendData = { "power": power, "vehicle": vehicle }; $.ajax({ type: ...

Can you explain the variances between ngx-translate and ngx-i18next for me?

As ngx-i18next serves as a wrapper for i18next, I am curious about the specific differences in translation capabilities between ngx-translate and i18next. ...

Retrieving the source code of a specific http URL using JavaScript

Is it feasible to obtain the source code of a webpage using JavaScript on the client side? Perhaps with AJAX? However, can I ensure that the server from which I am downloading the URL sees the client's IP address? Using AJAX could potentially reveal ...

if statement for a method within the ng-click directive

Whenever I click the button, I want to either execute createRole() if RoleName is not set or EditRole() method if RoleName is set. However, for some reason, EditRole() is being executed for both cases. <button type="submit" ng-click="selectedItem.Rol ...

Apollo client combines objects when the 'id' property is not specified

When I query data from my Apollo server, it follows a specific structure as shown below: hero { image { id name mimeType url } title description } welcome { image { id name mimeType ...

Tips on Avoiding Initial Click Activation

I've been working on a JavaScript function that dynamically generates an iframe with a button that, when clicked, deletes the iframe itself. Here are the functions I've written: function createIframe (iframeName, width, height) { var ifram ...

Tips for showcasing elements individually in JavaScript when a button is clicked and halting on a random element

I have some names stored in h3 tags. I want to highlight one name at a time when I click a button, stopping at a random name. <div class="all-names"> <h3 class="name-one"><span class="line">Name ...

JavaScript code failed to run

I am currently attempting to invoke a JavaScript script to export a chart from the PrimeFaces chart component. The issue I am facing is that the base64str variable appears to be null, and the script responsible for populating this value is not being called ...

Upgrade your Angular 6 project from bootstrap 3.3.7 to 4.0 with these expert tips

As I embark on my first Angular 6 project, I started by installing Bootstrap 3.3.7 using npm. After exploring some exciting carousels and features on this site, I realized that Bootstrap 4.0 is required for implementation. Can someone guide me on how to ...

Problem with IE off-canvas scrolling

Currently, I am facing an issue with the scrolling functionality of an off-canvas sidebar on my Joomla 3 website. It seems to be working fine in Chrome and Firefox, but when it comes to Internet Explorer, the visible scroll bar refuses to move when attempt ...

Verify whether a certain key exists within the gun.js file

Suppose I need to verify whether a specific entry exists in the database before adding it. I attempted the following: gun.get('demograph').once((data, key) => { console.log("realtime updates 1:", data); }); However, I only receive ...

What is the best way to see if a variable is present in TypeScript?

I am facing an issue with my code that involves a looping mechanism. Specifically, I need to initialize a variable called 'one' within the loop. In order to achieve this, I first check if the variable exists and only then proceed to initialize it ...

The form reset function came back as null in the results

I'm attempting to reset the form inputs with the following code: $("#form_employee_job")[0].reset(); Even after executing the code, the inputs remain filled and the console shows undefined What am I overlooking? https://i.sstatic.net/sqzzZ.jpg ...

Tips for displaying real-time error notifications from server-side validation using AJAX

Seeking a way to display inline error messages from my Symfony2 Backend without refreshing the page. I considered replacing the current form in the HTML with the validated form containing the error messages returned by the backend through AJAX. However, ...