Can't disable Twitter load button with jQuery?
I am doing AJAX on button click
$btn.button('loading');
$.ajax({
type: 'PUT',
url: 'event/',
data: put_data,
dataType: 'json',
success: function(data){
if (data.redirect) {
window.location = data.redirect;
}
else {
$btn.button('reset');
if ($btn.is('#my-btn')) {
console.log('disabling button');
$btn.prop('disabled', true);
}
}
}
});
disabling button
is displayed in the console, but the button is not disabled. The boot and reset button works very well. I tried .addClass('disabled')
and .attr('disabled','disabled')
, but they also don't work.
See it here: http://codepen.io/anon/pen/Wvbeeg
source to share
The problem is what button('reset')
is asynchronous. You can follow the html changes and see that they are not immediate.
A little delay after reset fixes the problem, but personally I would just program the whole process myself instead of using the bootstrap API
$(document).ready(function() {
$('#mybutton').click(function() {
var $btn = $(this);
$btn.button('loading');
setTimeout(function() {/// mimic ajax delay
$btn.button('reset');
setTimeout(function() {// short delay after reset
$btn.prop('disabled', true);
}, 200);
}, 1000);
});
});
source to share
You have to attach the disabled attribute so the Bootstrap button can style (this is a CSS style based on the html attribute)
[...]
$trigger.attr("disabled", true);
[...]
You can see a working example here: http://codepen.io/anon/pen/oXNRww (the ajax request has been replaced with setTimeout)
source to share
Delete
$btn.button('reset');
For some reason, this is not evaluated until you disable it. (This is asynchronous)
Instead of resetting the button with the "reset" code, it would be better to just delete the property disabled
if it exists. This will effectively activate the button if it should be active.
Modified code:
$btn.button('loading');
$.ajax({
type: 'PUT',
url: 'event/',
data: put_data,
dataType: 'json',
success: function(data){
if (data.redirect) {
window.location = data.redirect;
}
else {
if ($btn.is('#my-btn')) {
console.log('disabling button');
$btn.prop('disabled', true);
} else {
$btn.prop('disabled', false);
}
}
}
});
Bonus tip: don't use .removeProp () to re-enable the button. This will completely remove the property and you will no longer be able to use it. More on prop () here: https://api.jquery.com/prop/
source to share