Disable button after being clicked once - Using HTML, CSS, and JavaScript

Why is the following method not functioning as intended? I aim to have the JavaScript code execute when the button is clicked once, and then have the button disabled and 'grayed-out' so it cannot be clicked again.

$(document).ready(function() {
  $('#contact-submit').on('click', function(e) {
    e.preventDefault();
    var btn = $(e.target);
    btn.attr("disabled", "disabled"); // disable button
    var url = 'https://hooks.slack.com/services/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
    var text = 'xxxxxxxxxxxxxxxxxxxxxxxxx'
    $.ajax({
      data: 'payload=' + JSON.stringify({
        "text": text
      }),
      dataType: 'json',
      processData: false,
      type: 'POST',
      url: url
    });
  });
});
#contact button[type="submit"] {
  cursor: pointer;
  width: 100%;
  border: none;
  background: #4CAF50;
  color: #FFF;
  margin: 0 0 5px;
  padding: 10px;
  font-size: 15px;
}

#contact button:disabled[type="submit"] {
  cursor: pointer;
  width: 100%;
  border: none;
  background: #ffffff;
  color: #FFF;
  margin: 0 0 5px;
  padding: 10px;
  font-size: 15px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button name="submit" type="submit" id="contact-submit" data-submit="...Sending">Call</button>

Answer №1

Make sure to re-enable the button after making an AJAX call. You can use two helpful events to handle the callback result of the AJAX call:

  1. success
  2. error

$(document).ready(function() {
  $('#contact-submit').on('click', function(e) {
    e.preventDefault();
    var btn = $(e.target);
    btn.attr("disabled", "disabled"); // disable button
    var url = 'https://hooks.slack.com/services/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
    var text = 'xxxxxxxxxxxxxxxxxxxxxxxxx'
    $.ajax({
      data: 'payload=' + JSON.stringify({
        "text": text
      }),
      dataType: 'json',
      processData: false,
      type: 'POST',
      url: url,
      success: function(data) {
        console.log("OK")
        btn.removeAttr("disabled");
      },
      error: function(data) {
        btn.removeAttr("disabled");
      }
    });
  });
});
#contact button[type="submit"] {
  cursor: pointer;
  width: 100%;
  border: none;
  background: #4CAF50;
  color: #FFF;
  margin: 0 0 5px;
  padding: 10px;
  font-size: 15px;
}

#contact button:disabled[type="submit"] {
  cursor: pointer;
  width: 100%;
  border: none;
  background: #ffffff;
  color: #FFF;
  margin: 0 0 5px;
  padding: 10px;
  font-size: 15px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button name="submit" type="submit" id="contact-submit" data-submit="...Sending">Call</button>

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

Exploring the potentials of REST services using the .Net 2.0 framework in conjunction with integrating REST consumption in JavaScript

According to Wikipedia, REST is defined as REST is considered to be the architectural style of the World Wide Web. It was developed alongside the HTTP/1.1 protocol, while building upon the design of HTTP/1.0 The practices of REST have been in existence ...

"When using FireFox, you can easily create a hyperlink that scrolls to a specific section of a webpage,

I have created a style for image button: .sticky { position: fixed; top: 50px; width: 120%; z-index: 1; } @media screen and (min-device-width : 100px) and (max-width: 600px) { .sticky{ display:none; } } and also implemented a script for it: ...

Is there a way to display JSON data within my AJAX success callback function?

I'm encountering an issue where the JSON data returned from the server is not accessible in my success callback function within an AJAX request. $.ajax({ url:'myData.php', type:'post', success:function(data){ c ...

Trouble arises when implementing a nested flex layout in Angular Material shorthand

I'm having trouble identifying the issue with this particular layout. My goal is to maintain a Single Page Application layout where the "deepest" component only becomes scrollable if the viewport height is too small, as indicated in the snippet by us ...

The functionality of the Express module in a Node.js environment is not functioning as

I am currently utilizing the 'express' module within Node JS following the example here Upon attempting to run the server and accessing 'localhost:8000', I encounter the following error: Error: No default engine was specified and no e ...

Do colors appear differently on various screens?

I've noticed that the background color #1ABC9B appears differently on various monitors when viewing my website. On MAC systems and smart phones, it appears as a lighter shade of green compared to other laptops where it appears darker. What could be ca ...

Tips for dynamically adjusting an iframe's content size as the browser window is resized

Currently, I am in the process of building a website that will showcase a location on a map (not Google Maps). To achieve this, I have utilized an iframe to contain the map and my goal is for the map to adjust its width based on the width of the browser wi ...

What could be causing this template to malfunction?

Every time I try to start my Express server and access the page, I encounter an error. Can anyone pinpoint what might be wrong with the syntax? The "startzeit" property is a Date() Object. <tbody> <% for (let seminar in seminare){ %> ...

The presentation of the Google graph with dynamically changing data appears to be displaying inaccurately

I am looking to incorporate a graph displaying sales and purchase data on my webpage. Users should be able to select from categories like Purchase, Sales, or Production. I have separate tables for Purchase (AccPurchase) and Sales (AccSales), with productio ...

Material-ui does not adjust Typography color based on the theme selected

Exploring material-ui, I have implemented two themes: const darkTheme = createMuiTheme({ palette: { type: "dark" } }); const lightTheme = createMuiTheme({ palette: { type: "light" } }); However, when utilizing the Typography component, t ...

What's the best way to arrange my containers for optimal placement?

I'm attempting to create a Thymeleaf template for rendering a printable PDF. Here is what I currently have: <html xmlns:th="http://www.thymeleaf.org" > <head> <meta name="viewport" content="width=device-width, initial-scale=1.0" ...

Determine if the html element is wrapping to a new line when zoomed in or when the text size on Windows is increased

My webpage has 2 labels displayed side by side, but due to the system text size being set at 150% (which is recommended) in Windows, the second label does not have enough space and gets pushed below the first label. I am looking for a way to determine if t ...

Failed to make a request to https://registry.npmjs.org/node-modules because of an error: error:0906D06C:PEM routines:PEM_read_bio:no start line

Encountering an issue while attempting to install a JS package. Despite conducting thorough research, I have not been able to resolve the error. Please help me identify where I am going wrong. npm ERR! request to https://registry.npmjs.org/node-modules ...

Tips for showcasing a dataset within a table using Angular.js ng-repeat

I am encountering an issue where I have to present an array of data within a table using Angular.js. Below is an explanation of my code. Table: <table class="table table-bordered table-striped table-hover" id="dataTable" > <tbody> ...

The output of the Node.js crypto.pbkdf2 function may not match the result obtained from CryptoJS.PBKDF

Currently, I am utilizing PBKDF2 on both the frontend with CryptoJS and the backend with Node.js. Despite using the identical salt, algorithm, number of iterations, and password, the derived keys are turning out to be different. Below is the code snippet ...

The table's width exceeds the appropriate size

Take a look at the code snippet below <%-- Document : index Created on : Feb 7, 2014, 1:03:15 PM --%> <%@page import="java.util.Map"%> <%@page import="java.util.Iterator"%> <%@page import="analyzer.DataHolder"%> <%@p ...

Utilizing props to transfer data between components in ReactJS

I have a React application where I am binding text values when a specific div is clicked. However, I am now faced with the challenge of passing these text values to another component using props. This is what my code looks like: class PostOptionBar exten ...

Ways to extract information from nested JSON arrays in objects?

We are currently developing an Extension for WeClapp, with Custom Attributes that can be added to various Datatypes within the platform. These Attributes are accessible through a nested JSON object Array. Here is an example of the interface: export inter ...

The Power of Jquery's load() Function for Loading Text

Is there a way to show the content of file.txt along with any text on the <title id="mytitle"></title> tag? $(window).on('load', function() { $("#mytitle").load("/file.txt"); }); The content of file ...

Having issues with the Jquery tablesorter plugin when attempting to prevent headers from being sorted

Can anyone help me with a sorting issue I am having with a table on my website? I am using the jQuery plugin tablersorter to sort the table, but I have two headers that I do not want to be sortable. I tried to disable them using the example provided on the ...