'disable button not working in jquery and ajax
I want to disable the submit button after the user clicks on the submit button in the HTML form. But form redirects directly to the next page without disabling the button.
The ideal sequence is:
- User clicks the submit button
- Validation is performed
- Submit button disables
- Form Data is submitted to the database/ spreadsheet
- User is redirected to thank you page
With the following code, the only issue is that the submit button is not getting disabled and everything else is working perfectly. Please suggest an alternative to fix the code. I am using WordPress which runs on jquery 1.4.1. So, $input.prop('disabled', true) also did not work
HTML:
<form id="test-form" method="post" name="test-form" action="">
<div>
<input class="input-field" name="Name" required type="text" placeholder="Enter name" />
</div>
<div>
<input class="input-field" name="Phone" required type="number" placeholder="Enter number" />
</div>
<div><button id="submit-form" class="btn" type="submit" name="submit-form">Submit</button></div>
</form>
JQUERY
var $form = $('form#test-form');
url = 'https://abcd';
$form.submit(function(e) {
$('submit-form').attr('disabled', 'disabled');
var jqxhr = $.ajax({
url: url,
method: "GET",
dataType: "json",
data: $form.serializeObject()
}).success(function() {
location.replace("/thank-you/");
});
e.preventDefault();
});
});
Solution 1:[1]
you are given id was wrong. try this
$(function(){
var $form = $('#test-form');
url = 'https://abcd';
$form.submit(function(e) {
e.preventDefault();
$('#submit-form').attr('disabled', 'disabled');
var jqxhr = $.ajax({
url: url,
method: "GET",
dataType: "json",
data: $form.serializeObject()
}).success(function() {
location.replace("/thank-you/");
});
});
});
Solution 2:[2]
$('#button').attr("disabled", true);
$.ajax({
url: url,
data: data,
type: 'post',
dataType: 'json',
cache: false,
async: true,
complete: function(response){
$('#button').attr("disabled", false);
},
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Krishna Jonnalagadda |
Solution 2 | Guru |