How to Toggle the Submit Button Using jQuery

I have implemented a feature using jQuery to disable the submit button and display a loading image. Here is how I have set it up:

The HTML structure for the submit button looks like this:

<div id="registerbtn" name="registerbtn">
  <input type="submit" class="btn btn-primary" icon="ok white" value="Register" id="register" name="register"/>
</div>
<div class="span4" style="display:none;" id="loadingtext">
  <img src="images/loading.gif" alt="Loading Image">                     
</div>

And in my jQuery script, I have the following code:

$(document).ready(function() {

    $('#register').click(function() {
        $('input[type="submit"]').attr('disabled','disabled');
     });
    $("#loadingtext").show();
});

However, the issue I am facing is that the button remains disabled permanently. How can I remove this functionality when needed?

Answer №1

Utilize the .prop() method along with $(this) to access the target element in the callback function

jQuery(function($) {

  const $register = $("#register"),
        $loading = $("#loading");

  $register.on("click", function() {
  
    $(this).prop('disabled', true);
    $loading.show();
    
    setTimeout(function() {
      $register.prop('disabled', false);
      $loading.hide();
    }, 2000);

  });

});
<input id="register" value="Register" type="submit">
<div id="loading" style="display:none;">Please wait for 2 seconds...</div>


<script src="//code.jquery.com/jquery-3.1.0.js"></script>

Answer №2

For information on how to disable or enable a form element, check out the jQuery FAQ page

How can I disable or enable a form element?
There are two methods for disabling or enabling form elements.

You can set the 'disabled' attribute to true or false:

// Disable #x
 $('#x').attr('disabled', true);
 // Enable #x
 $('#x').attr('disabled', false);

Alternatively, you can add or remove the 'disabled' attribute:

// Disable #x
 $("#x").attr('disabled', 'disabled');
 // Enable #x
 $("#x").removeAttr('disabled');

Update: According to the FAQ, the recommended way to do this now is:

// Disable #x
$( "#x" ).prop( "disabled", true );

// Enable #x
$( "#x" ).prop( "disabled", false );

Answer №3

If you want to get rid of the button permanently

$('#register').remove();

If you want to bring back the button

$('#register').attr('disabled',false);

Answer №5

Toggle properties on/off

 $('#apply-coupon').prop('disabled', function(_, value) {
  return !value;
});

Ensure disabled properties are active

$('#apply-coupon').removeAttr('disabled');

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

Switch from using a stylesheet to implementing jQuery

In order to achieve real-time replacement, the style changes immediately after a user interaction: $('link#mystyle').attr('disabled', 'disabled'); $('link#mystyle').remove(); if(new_style){ $('head').ap ...

What is the best way to embed an image into HTML code?

I am trying to enhance the appearance of a phone number inside an HTML code that is loaded into a UIWebView by adding a background image. NSString *stringToReplace = [NSString stringWithFormat:@"<a style=\"color:white; background-color:#707070; te ...

Utilizing jQuery-dependent plugins in a Create-React-App: A comprehensive guide

Looking to integrate bootstrap and other jQuery plugins like datepicker and carousel into my React app that is built with create-react-app. This is the method I am using to import jQuery and bootstrap: import React, { Component } from 'react'; ...

Implementing CSS Transform for Internet Explorer

Hello, is there a way to make this function in IE ?? I have been looking into IE transformations but it appears that they are not supported.. Is there an alternative method or something else? It works in other browsers like Firefox, Chrome, and Opera. I s ...

Using Jquery to create a popup when clicking on a dynamic anchor tag

I have a series of dynamic anchor tags presented below. Each anchor tag is part of a loop. When any of these links are clicked, I want to trigger a jQuery AJAX post request and display the response in a popup div. How can this be achieved? <script la ...

Using CSS for hover transitions can be glitchy in Safari, especially when trying to keep images centered

After seeing an example on Design Shack, I was inspired to create linkable photos that zoom in slightly when hovered over. To achieve the desired centered animation effect, I had to tweak the top, left, margin-top, and margin-left properties until it worke ...

What causes the difference in behavior between Firefox and Chrome when it comes to multiple column rendering and the use of overflow

Recently, I came across an interesting issue in Firefox related to lists inside a div with columns:2 set. In Firefox, when overflow:hidden is applied to the list, it stops rendering in 2 columns. However, in Chrome, the list continues to render in 2 colum ...

Prevent the loading of a <img> element and replace it with a new one using CSS

Is there a way to hide an <img> element without accessing the HTML directly, only by using CSS? The <img> element does not have any specific class. Here is the HTML markup: <img title="Manual" id="imgAjuda" src="images/ico_aj.png" width=" ...

Effortless sliding panel that appears on hover and vanishes when mouse is moved away

I am in the process of creating a menu for my website that utilizes linkbuttons which trigger additional linkbuttons to slide down upon hover. The desired effect is a smooth sliding panel that appears when hovering over the linkbutton, and disappears when ...

Is there a way to retrieve the ID by using the autocomplete feature to search for a user's first name and last name in PHP

Check out this code from index.php (all credit to the original owner): <HTML> <HEAD> <TITLE> Ajax php Auto Suggest </TITLE> <link href="css/style.css" rel="stylesheet" type="text/css"> <SCRIPT LANGUAGE="JavaScript ...

What could be the reason for the mouseleave event not functioning properly?

I have a JSFiddle that is working perfectly. Check out my Fiddle here. In my code, I am trying to make a div change colors when hovered over and then back to its original color when the mouse moves out. It works fine on JSFiddle but not locally. When I r ...

The functionality of the CSS transform property seems to be malfunctioning

My HTML and CSS code displays texts in two blocks within a dl element. I attempted to change the ▶ symbol to a different shape using the css transform scale property. However, some browsers only show the triangle in the first column. Why is this happenin ...

I'm looking to make my PayPal donate button smaller after noticing that PayPal is making it larger. How can I adjust the size of my customized PayPal

I am seeking your help in resolving an issue with PayPal enlarging my button from 130px x 65px to 300px x 150px. I have checked the button on both a local browser and within the Square Space editor, but the result remains the same. I even attempted to adju ...

The validation did not pass using the validate.min.js script

Hey everyone, I had this code working perfectly before but now it seems to have stopped working. Can anyone help me figure out what's going on? Below is the form I am referring to: <form action="CreateUser" method="POST" id="subscribe"> & ...

Looking for guidance on utilizing pushState and handling onpopstate events?

By using ajax, I am able to load specific page content without refreshing the entire page. In order to make the back button functionality work, I utilize pushState and onpopstate as shown below: function get_page(args){ .... $.ajax({ url ...

jQuery's Multi-Category Filter feature allows users to filter content

I have been working on creating a filter function for my product list. The idea is that when one or more attributes are selected, it should fade out the elements that do not match. And then, if a filter is removed, those faded-out items should fade back in ...

PHP response is blank when password_hash or password_verify functions are used

My application utilizes JavaScript to retrieve a string and send it via POST to a PHP file on the server for processing. The PHP receiver is responsible for parsing the string, performing tasks, and sending back status updates to JavaScript. However, after ...

When using the .append method in jQuery, the JSON array only displays the last value of the array when iterating through it with

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <html> <head> <title>Displaying Array Data in Table Using Javascript</title> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">& ...

Using C# to make an AJAX request

//Custom JavaScript function function UpdateAndSaveProjectRecords() { var CompanyCode = ''; var ProjectName = ''; var ProjectDescription = ''; var ProjectType = ''; ...

Discover the steps to download web page data using Objective-C while ensuring that JavaScript has finished executing

I attempted something similar: NSString *url = @"http://www.example.com"; NSURL *urlRequest = [NSURL URLWithString:url]; NSError *error = nil; NSString *htmlContent = [NSString stringWithContentsOfURL:urlrequest encoding:NSUTF8StringEncoding error:&e ...