简体   繁体   中英

Disable the button after clicking using jquery

I am working on opencart. I dont want my users to buy multiple products they can buy only 1 product with 1 customer id, so for this i want my add to cart button to help me. I want this button to be disabled (read only) if add to cart process is performed successfully.

HTML:

 <button type="button" id="button-cart" data-loading-text="<?php echo $text_loading; ?>" class="btn btn-primary btn-lg btn-block"><?php echo $button_cart; ?></button>

Jquery:

<script type="text/javascript"><!--
$('#button-cart').on('click', function() {
$.ajax({
    url: 'index.php?route=checkout/cart/add',
    type: 'post',
    data: $('#product input[type=\'text\'], #product input[type=\'hidden\'], #product input[type=\'radio\']:checked, #product input[type=\'checkbox\']:checked, #product select, #product textarea'),
    dataType: 'json',
    beforeSend: function() {
        $('#button-cart').button('loading');
    },
    complete: function() {
        $('#button-cart').button('reset');
    },
    success: function(json) {
        $('.alert, .text-danger').remove();
        $('.form-group').removeClass('has-error');

        if (json['error']) {
            if (json['error']['option']) {
                for (i in json['error']['option']) {
                    var element = $('#input-option' + i.replace('_', '-'));

                    if (element.parent().hasClass('input-group')) {
                        element.parent().after('<div class="text-danger">' + json['error']['option'][i] + '</div>');
                    } else {
                        element.after('<div class="text-danger">' + json['error']['option'][i] + '</div>');
                    }
                }
            }

            if (json['error']['recurring']) {
                $('select[name=\'recurring_id\']').after('<div class="text-danger">' + json['error']['recurring'] + '</div>');
            }

            // Highlight any found errors
            $('.text-danger').parent().addClass('has-error');
        }

        if (json['success']) {
            $('.breadcrumb').after('<div class="alert alert-success">' + json['success'] + '<button type="button" class="close" data-dismiss="alert">&times;</button></div>');

            $('#cart > button').html('<i class="fa fa-shopping-cart"></i> ' + json['total']);

            $('html, body').animate({ scrollTop: 0 }, 'slow');

            $('#cart > ul').load('index.php?route=common/cart/info ul li');
        }
    }
});
});//--></script>

I know this will do the trick

$(this).attr('disabled', true);

But iam not finding the best position for it. I want the button to be disabled if the validation is all done and product is entered in cart area

jQuery.attr()

Get the value of an attribute for the first element in the set of matched elements.

whereas,

jQuery.prop()

Get the value of a property for the first element in the set of matched elements. 

Before jQuery 1.6 , the attr() method sometimes took property values into account when retrieving some attributes, which caused in inconsistent behavior. And thus, the prop() method was introduced. As of jQuery 1.6. , the .prop() method provides a way to explicitly retrieve property values, while .attr() retrieves attributes.

According to your code you are highlighting error by $('.text-danger').parent().addClass('has-error'); . So you can use prop('disabled', true) instead of $(this).attr('disabled', true); and add it to just after $('.text-danger').parent().addClass('has-error');

 $('.text-danger').parent().addClass('has-error');
 $(this).prop('disabled', true)

I see that you are relying on the response from your service call to validate success or error.

In that case it will be better to disable the button as soon as your service is called, and wait for response.

After response if your validation is successful, then no worries, else re-enable button and notify user the error and ask to make changes if required.

So the code could be like this,

$('#button-cart').on('click', function() {
        var _button_ref = this;
                $(_button_ref).attr('disabled', true);
                $.ajax({
                url: 'index.php?route=checkout/cart/add',
                        type: 'post',
                        data: $('#product input[type=\'text\'], #product input[type=\'hidden\'], #product input[type=\'radio\']:checked, #product input[type=\'checkbox\']:checked, #product select, #product textarea'),
                        dataType: 'json',
                        beforeSend: function() {
                        $('#button-cart').button('loading');
                        },
                        complete: function() {
                        $('#button-cart').button('reset');
                        },
                        success: function(json) {
                        $('.alert, .text-danger').remove();
                                $('.form-group').removeClass('has-error');
                                if (json['error']) {
                        // your logic
                        $(_button_ref).attr('disabled', 'false');
                        }

                        if (json['success']) {
                        // your logic
                        }
                        }
                });

Also, it will be better if you have error call back function, to handle if service fails.

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