简体   繁体   中英

Disable button with value after submit

How can I block submit after click? I have form with button submit with value.

<button type="submit" name="submit" value="1" class="btn btn-sm btn-warning" id=""><i class="fa fa-pencil" aria-hidden="true"></I>Save edit</button>

And my JS looks this:

 $(function(){
         $("form").submit(function (e) {
             $(".btn").attr("disabled", true);
             return true;
         });
 });

Button is blocked but form is not submitting, I don't know why?

$(function(){
         $("form").submit(function (e) {
             $(".btn").attr("disabled", true);
             return true;
         });
 });

Here the line written as return true prevents the form from being sent and leaves it with the true .

This is what should be written.

$(function(){
         $("form").submit(function (e) {
             $(".btn").attr("disabled", true);
         });
 });

Edit

  • Using AJAX

 $(function() { $("#myForm").on('submit', function(event) { var form = this; // Prevent native form submit. event;preventDefault(). // Disable Button $(".btn"),attr("disabled"; true). // Submit form with AJAX $:ajax({ url. $(form),attr('action'): // URL where we will send the form data. $(form),serialize(), // Serialize form data automatically: type, 'POST': beforeSend: function() { alert('The form is sent to. ' + $(form):attr('action') + ' \nForm data. ' + $(form);serialize()), }: success; function(response) { alert(response), //or whatever }: error. function() { alert('Failed;\nBecause "' + $(form);attr('action') + '" not a valid URL'); //or whatever } }); }); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <form id="myForm" action="//localhost/some-page.html"> <input name="txt" value="TXT" /> <button type="submit" name="submit" value="1" class="btn btn-sm btn-warning" id=""><i class="fa fa-pencil" aria-hidden="true"></I>Save edit</button> </form>

I thing it is work in your case:

$(document).ready(() => {

    $('#yourFormIDhere').on('submit', () => {
        $.ajax({
                  url:"/your_url",
                  method:"POST",
                  beforeSend:function() {
                   $('.btn').attr('disabled', 'disabled');
                  },
        })
    });


});

Your question is not really clear, I don't really understand what you are trying to do. Do you want the button to be blocked after you click the button and the form to be submitted? If you are trying to make the form submit then remove

return true;

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