简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM