PrimuS PrimuS - 2 months ago 10
Ajax Question

Update class array after $.ajax

I have a set of buttons in a list, some of them have a

disabled
class.

What I want to do

When I click a non-disabled button I want to add disabled to ALL the buttons. After finishing the ajax request, I want to have only the previously AND the clicked button to have a
disabled
class.

I tried

$(document).on('click', '.myButton', function (e) {

/* Get this Button */
var $btn = $(this);

/* Get all disabled Buttons */
var allDisabled = $('.disabled');

/* Add disabled to all buttons */
$('.buttonAction').addClass('disabled');

/* Do Ajax Stuff */
$.ajax({
type: 'GET',
...
success: function (data) {

/* Remove all 'disabled' from Buttons */
$('.buttonAction').removeClass('disabled');

/* Add 'disabled' to this Button */
$btn.addClass('disabled');

/* Add 'disabled' to all previous Buttons */
allDisabled.each(function(){
$(this).addClass('disabled');
});
},
...

});
});


Unfortunately the
allDisabled.each
function assigns the
disabled
to ALL buttons.

WHere am I wrong?

Answer

Instead of removing and adding a class to all objects, you can only manipulate with those buttons which need to be temporarily disabled:

$(document).on("click", ".my-button", function() {
    var $btn = $(this);
    var $disableDuringAjax = $(".buttonAction:not(.disabled)").addClass("disabled");

    $.ajax({
        type: 'GET'
    })
    .done(function (data) {
       $disableDuringAjax.removeClass("disabled");
       $btn.addClass('disabled');
    });
});

That way, disabled class will not be toggled twice for buttons, which should not be enabled at all.