简体   繁体   中英

Disabling and enabling html tag to prevent multiple clicks

I have this jQuery structure:

$(document).on('click', '.view-details', function () {   
    $(this).prop("disabled", true);
    // API call1
    // API call2
    // API call3
    $(this).prop("disabled", false);
}

I have done this disabling and enabling to prevent user from clicking multiple times which is causing multiple issues.

The problem with this is API calls are Asynchronous and I don't want to make them Synchronous.

But making them Async would execute Line5 before API calls which i dont want. Making it enabled on each APIs success and error is also too much of an effort.

Any other better suggestion to make sure line 5 executes after completion of 2,3,4?

您可以使用以下方式:

$.when(api1, api2, api3).done(function(){});

You can put the deferred objects returned by the AJAX calls in an array and then apply that to $.when to enable the button once all the requests have completed. Try this:

$(document).on('click', '.view-details', function () {   
    var $el = $(this).prop("disabled", true);
    var requests = [];
    requests.push(request1);
    requests.push(request2);
    requests.push(request3);

    $.when.apply(requests).done(function() {
        $el.prop("disabled", false);
    });
});

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