Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - Proper way of disabling buttons on submit

Tags:

jquery

My question is what's the best approach to implement disabing of buttons on page with jQuery after any of the buttons for form submit is clicked. Something similar is available here Is js executed after form synchronized submit where it's stated that my code in question (1.) "may" run. All code is on document ready.

  1. I've seen code like that in our project, but is it really guaranteed that the last line - button("disable") is invoked?

    $("#saveButton").on("click", function () {
        $("#myForm").submit();
        $("#saveButton").button("disable");
    });
    
  2. Alternative would be this (it could be problematic, if button would get disabled, but he last line could also fail, so it doesn't really "feel good".

    $("#saveButton").on("click", function () {
        $("#saveButton").button("disable");
        $("#myForm").submit();
    });   
    
  3. This is probably the best approach, right? Can there be any "gotchas"?

    $("#myForm").submit(function () {
        $("#saveButton").button("disable");
        // disable also all the elements that can do a submit
        return true;
    });
    
like image 628
the berserker Avatar asked Dec 18 '25 20:12

the berserker


1 Answers

Submit is nearly the best approach, the "One" approach will give you only one chance, if your submit fails or not validates you are stucked

$('#myForm').on('submit',function () {
    $('#saveButton').button('disable');
    // disable also all the elements that can do a submit

    //Validate
    if (validate)
        return true;
    else  {
         //cancels submit
         $('#saveButton').button('enable');
         return false;
    }
});
like image 127
Roger Barreto Avatar answered Dec 21 '25 10:12

Roger Barreto



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!