Disable the form after submission using Bootstrap 5

How can I submit a form using the Post method in Bootstrap v5 and then indicate that the form is being processed? I've encountered numerous examples for Bootstrap v4 and jQuery, but since Bootstrap v5 no longer supports jQuery and there are potential compatibility issues, I'm looking for a solution specific to Bootstrap v5.

Below is a simplified version of the form I'm working with:

<form action="" method="post" id="reqform">
  <div class="input-group">
    <div class="form-floating mb-3">
      <input class="form-control " id="nameInputId" placeholder="name" name="name" aria-describedby="basic-addon1" type="text">
      <label for="nameInputId">Name</label>
    </div>
  </div>
  
  <button type="submit" id="submitBtnId" class="btn btn-primary">Submit</button>
</form>

I attempted to implement the following script at the end of the file:

// Display loading state when submit button is clicked
submitBtnElm = document.getElementById("submitBtnId")
submitBtnElm.addEventListener("click", function () {
    // Disable the button
    submitBtnElm.disabled = true;
            
    // Disable the remaining form fields
    document.getElementById("nameInputId").disabled = true;
            
    // Add a spinner to the button and change the text to 'Loading...'
    submitBtnElm.innerHTML = '<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span>Loading...'
});

In my testing on Chrome in CentOS 7, the form never gets submitted to the backend; only the loading button is displayed. On Firefox, the form is submitted but the name field value is not sent to the backend. Removing this JavaScript code resolves the issues.

I also tried using the onsubmit attribute in the form tag, but encountered the same issues:

<form action="" method="post" id="reqform"  onsubmit="return disableForm(this);"> 

My goal is to send the form data to the backend server first, then display the loading button and disable other fields. I'm seeking a method to ensure the JavaScript code doesn't interfere with the data submission. I want the form to be submitted to the backend server even if JavaScript is disabled. While I've come across similar queries involving jQuery, none of the solutions seem to work for my case.

Update: I also attempted the following:

submitBtnElm.addEventListener("submit", function ()

I debugged the backend server execution flow and observed that the JavaScript code doesn't execute while the server processes the data. I aim to change the button and form as soon as the data is submitted so that the user cannot interact further.

Update 2 I discovered an article that suggests wrapping the form disabling code in a setTimeout function:

This approach worked for me in both Chrome and Firefox on CentOS 7. Unfortunately, I don't have access to a Mac for testing. Below is the updated code that yielded successful results:

submitBtnElm = document.getElementById("submitBtnId")
submitBtnElm.addEventListener('click', function(event) { 
            setTimeout(function () {
                event.target.disabled = true;
            }, 0);
});

I'm curious to know if this solution is cross-browser compatible according to JavaScript experts. If not, what alternative approach would you recommend? Another solution I found involved replacing the functional button with a non-functional one displaying a 'loading' message.

Answer №1

Incorporate JavaScript to develop a function that activates when the form is submitted. Integrate a disabled class into the form using a basic if statement.

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

Adjust the position of elements based on their individual size and current position

I am faced with a challenge regarding an element inside a DIV. Here is the current setup... <div id="parent"> <div id="child"></div> </div> Typically, in order to center the child within the parent while dynamically changing i ...

Unique Tags and Javascript: A customized approach

In the process of developing a web application, I am aiming for high standardization. To achieve this goal, I plan to utilize custom namespace tags that will be modified by JavaScript based on their functionality. For instance: <script type="text/java ...

Unable to retrieve cookies from the client side | Working with NodeJS and JavaScript

Code for Handling Cookies on the Server-Side: res.cookie('test', 'value', { expire: 400000 + Date.now(), httpOnly: false }); res.writeHead(302, { 'Location': 'localhost:4000/test', }); res.end(); Code for Acce ...

What is the best way to pass an Id to JavaScript's getElementById when the Id from my input tag is produced by the output of PHP/MySQL?

Thank you in advance for your assistance. I am attempting to search through all the IDs listed below to determine if the user has selected any data. <input id=\"".$row['childName']."\" type=\"checkbox\" name=\"foodDa ...

Can one button be clicked to trigger the activation of another button through a click?

Just as the title suggests, I am wondering how to make this happen? Any guidance would be greatly appreciated! $('.notVisible').click (function(){ alert("I'm the invisible button") }); $('.visible').click (function(){ al ...

Tips for validating form input upon submission in Angular 6

Within my Angular application, I have successfully implemented form validators. However, I am aiming to trigger form validation specifically upon submission. This means that when the user clicks on the submit button and the form is invalid, the errors indi ...

Struggling to align text on Bootstrap Card correctly

I need to create a leaderboard layout for a work project. The style I'm aiming for is based on Bootstrap elements, specifically aligning numbers to the right and ensuring they are vertically aligned. Refer to the provided image for a visual representa ...

Using SVG graphics as data labels in a HighChart stacked column chart

I am attempting to generate a stacked column chart in Highcharts with SVG images as x-axis labels, similar to the image displayed here: https://i.stack.imgur.com/y5gL1.png I have managed to achieve this with individual data points per label (non-stacked ...

Trouble linking JavaScript and CSS files in an Express App

Could someone assist me in understanding what is causing my code to malfunction? Why is it that my javascript and css files do not execute when the server sends the index.html file to the browser? I have a simple setup with an html page, javascript file, ...

Retrieve information from an external JSON source

I am receiving data from an API and storing its JSON in a separate file. The unique URL for accessing this file is shown below: http://events.com/rsvp.php?id=1234 The JSON content on the specified page appears like this: { rsvp: true } Each contact ha ...

Is there a way to verify the presence of a service worker on a specific URL?

Is there a way for me to determine if external websites have a 'service-worker' or not? Here is what I think could work: Extract all the JavaScript files from the given URL Look for the string 'sw.js' (I am not entirely sure how to ...

Display and view .dwg files using Javascript, HTML, and Angular

Looking for a way to upload and preview .dwg format images on a page created using js/HTML/angularjs or Angular 2+? I've attempted to use a CAD viewer js library, but the lack of documentation has made it challenging. Has anyone successfully implement ...

Is there a way to dynamically enable ui-sref through element.append in Angular?

I am in the process of developing a pagination directive. Once the total_for_pagination data is filled, the appropriate HTML for the pagination gets generated. Here's my current HTML structure with a maximum of 50 per page: <pagination data-numbe ...

AngularJS button click not redirecting properly with $location.path

When I click a button in my HTML file named `my.html`, I want to redirect the user to `about.html`. However, when I try using `$location.path("\about")` inside the controller, nothing happens and only my current page is displayed without loading `abou ...

Accessing html form elements using jQuery

I'm having trouble extracting a form using jQuery and haven't been able to find a solution. I've tried several examples, but none of them display the form tags along with their attributes. Here is a sample fiddle that I've created: Sam ...

Devices such as CAC cards and smart cards are not being recognized by Chrome's WebUSB feature

I recently developed a script to identify all USB devices connected to Chrome using chrome.usb.getDevices. Surprisingly, the script successfully detected a second-generation iPod touch, a mouse, keyboard, and two unidentified items from Intel. However, it ...

Issue with conditional image source URL in NUXT component not functioning as expected

I am currently attempting to dynamically render an image source path based on the provided prop in the component. In case the image does not exist in the assets folder, I want to include a fallback path. Below is the code snippet for my image tag: <img ...

Creating animated direction indicators in the "aroundMe" style with ngCordova

I am attempting to recreate a compass or arrow similar to the one featured in the AroundMe Mobile App. This arrow should accurately point towards a pin on the map based on my mobile device's position and update as I move. I have been struggling to fi ...

Trouble with locating newly created folder in package.json script on Windows 10

I am facing an issue in my Angular application where I am trying to generate a dist folder with scripts inside it, while keeping index.html in the root folder. I have tried using some flag options to achieve this but seem to be stuck. I attempted to automa ...

What is the best way to determine if a variable exists within an array in Angular and JavaScript?

Currently, I am working on a project using Angular 6 with Laravel. In one part of my code, I am fetching an array in the frontend and need to check if a certain variable is present within that array. In PHP, you can easily achieve this using the in_array f ...