简体   繁体   中英

jquery/ajax - disable submit button on any form for 3 seconds upon click

I have searched and searched and found nothing that explains what I need.

I have a webscript that has dozens of forms all over the place. I need to disable the submit button for 3 seconds after submit is clicked on any form no matter what the id, class, or action of the form.

I found the following code:

$('#btn').click(function(){
    var btn = $(this);
    $.post('http://someurl.com',{delay: 3}).complete(function(){
btn.prop('disabled', false);
    });
btn.prop('disabled', true);

});

but this requires the form have an id of btn and it appears to require the form be "posted" to some page.

Is there a way to achieve this on all forms reguardless of the action being performed? So if its a signup form, it disables the "join" button for 3 seconds, if its a comment form, it equally disables the submit for 3 seconds after submitting comment, .... basically no matter what the form or action I want to disable the submit button for 3 seconds after click.

Is this even possible?

I have tried changing all instances of "#btn" to "input" but this doesn't seem to work. I am really not great at this stuff but seem to manage stumbling through things with the help of others.

The reason my question is NOT a duplicate of other questions is because I specifically stated "no matter what the id, class, or action of the form". The solutions presented on the other question do not specifically address this. Adding id's, classes, or the likes is not a remote possibility on a webscript with hundreds and hundreds of forms for various reasons (its a social networking script). The solution I marked as correct is the solution that did not require any attributes to be added to the html elements.

Try this.(pseudo-code, modify as needed):

$('#mybutton').on('click', function() {
    $('[type="submit"]').prop('disabled', true);
    setTimeout(function() {
        $('[type="submit"]').prop('disabled', false);
    }, 3000); // 3 seconds 
});

Why not just bind a separate event for adding the disabled with a delay? You can still keep your own click logic for posting. Just assign the below code to a container element, or even the body, and give all the buttons you want to affect a class .mybutton (or something else).

$('.container').on('click', '.mybutton', function(event) {
  setTimeout(function(){
    $(this).attr("disabled", false);
  }, 3000);
  $(this).attr("disabled", true);
});

If you want the disabled to toggle depending on the 'complete' event for each call, you would have to create a prototype function with parameters, that can be assigned to each button. The above is with 3 second delay though.

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