简体   繁体   中英

How to disable button after click in jQuery

Sometimes I am able to trigger the submit button twice. and the ajax is triggered twice too.

Here is my html code:

<div class="buttons-area">
    <input id="step-two" class="btn btn-primary" type="submit" value="Next step »">
</div>

And here is my ajax:

<script>
    $(document).ready( function () {

        $('#step-two').on('click', function(e) {

            e.preventDefault();

            var formData = new FormData();

            formData.append('username', $('#username').val());
            formData.append('email', $('#email').val());
            formData.append('password', $('#password').val());
            formData.append('password_confirmation', $('#password_confirmation').val());

            $.ajax({
                url:         'registration',
                method:      'post',
                processData: false,
                contentType: false,
                cache:       false,
                dataType:    'json',
                data:        formData,
                beforeSend: function()
                    {
                        $(".validation-error-inline").remove();
                    }
                })
                .done(function(data) {

                    if (data.validation_failed == 1)
                    {
                        var arr = data.errors;

                        $.each(arr, function(index, value)
                        {
                            if (value.length != 0)
                            {

                                $("#"+index).closest(".middle").next(".right")
                                            .append('<span class="text-error validation-error-inline">' + value[0] + '</span>');

                            }
                        });

                    }


                })
                .fail(function(jqXHR, ajaxOptions, thrownError) {
                    alert('No response from server');
                });
                return false;

        });
    });
</script>

How can I disable the button after the first click and allow the next click only if the ajax is finished?

Right now I am able to trigger the ajax two times in the row if I am fast and the same error message is shown twice.

Simply add $(this).attr("disabled", "disabled"); before return false .

And $(this).removeAttr("disabled"); if you want to enable button. Otherwise the button will be disabled until page refresh.

You can disable the button on click

$('#step-two').on('click', function(e) {
 e.preventDefault();
$(this).prop('disabled',true); //disable further clicks
…

And enable in the always() callback so that the button will be enabled after the request regardless it succeeded or not.

$.ajax({
            url:         'registration',
            method:      'post',
            processData: false,
            contentType: false,
            cache:       false,
            dataType:    'json',
            data:        formData,
            beforeSend: function()
                {
                    $(".validation-error-inline").remove();
                }
            })
.done(function(){
   // code
 })
.fail(function(){
   // code
})
.always(function(data) {
 $('#step-two').prop('disabled',false); // re-enable the button once ajax is finished
})

Try adding at the top of your click handler to disable the button

$('#step-two').prop('disabled', true);

And then add this before return false to reenable it:

$('#step-two').prop('disabled', false);
$(document).ready(function () {

    $('#step-two').on('click', function (e) {
        $(this).prop('disabled', true); // <-- Disable here

        e.preventDefault();

        var formData = new FormData();

        formData.append('username', $('#username').val());
        formData.append('email', $('#email').val());
        formData.append('password', $('#password').val());
        formData.append('password_confirmation', $('#password_confirmation').val());

        $.ajax({
            url: 'registration',
            method: 'post',
            processData: false,
            contentType: false,
            cache: false,
            dataType: 'json',
            data: formData,
            beforeSend: function () {
                $(".validation-error-inline").remove();
            }
        })
            .done(function (data) {
            $('#step-two').prop('disabled', false); // <-- Enable here notice we're in a different scope so `$(this)` won't work

            if (data.validation_failed == 1) {
                var arr = data.errors;

                $.each(arr, function (index, value) {
                    if (value.length != 0) {

                        $("#" + index).closest(".middle").next(".right")
                            .append('<span class="text-error validation-error-inline">' + value[0] + '</span>');

                    }
                });

            }


        })
            .fail(function (jqXHR, ajaxOptions, thrownError) {
            alert('No response from server');
        });
        return false;

    });
});

You have to disable your button after the ajax call, like this:

$('#step-two').on('click', function(e) {
   var $button = $(this);
   $button.attr('disabled', 'disabled');

But dont forget to enable it again if necessary. The best approach is to enable it in the "done" function

.done(function(data) {
  $button.removeAttr('disabled');
  ....

Regards.

add the code in click event:

 $("#step-two").prop("disabled", true)

when ajax complete:

$("#step-two").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