简体   繁体   中英

jQuery Click Event Delay

I have a button that triggers (1) the application of a coupon code and (2) the submission of the entire form for payment.

The problem is that the coupon code is taking a couple of seconds to apply so is applying after the entire form is submitted for payment. How can I delay the click of the second payment button so that the coupon code button is applied first?

<script type="text/javascript">
jQuery('.js-coll-button2').click(function(e) {
  e.preventDefault();
  jQuery('#sc_checkout_form_1').find('.sc-coup-apply-btn').click();
  jQuery('#sc_checkout_form_1').find('.sc-payment-btn').click();
});
</script>

That would be unwise. You have no guarantee that a certain amount of time will be always enough. It depends on the client's computer and connection, and what if the first action returns an error?

The best way to do this would be to fire the second function only if the first has completed.

Edit: I've never used Stripe from Javascript, but the API manual says clearly that every REST call returns a code.

And, you should not try to FORCE the clicks but use funcions instead. Decouple your functionality from the buttons!

<script type="text/javascript">

function doCoupon() {
     return $.ajax(... do your stripe call ...);
}

function doAnotherThing() {
    return $.ahax(... call your other thingie... );
}

function handleError() {
    // ... 
}

jQuery("#sc_checkout_form_1 .sc-coup-apply-btn").click(doCoupon);
jQuery("#sc_checkout_form_1 .sc-payment-btn").click(doAnotherThing);


jQuery('.js-coll-button2').click(function(e) {
  e.preventDefault();
    doCoupon().success(doAnotherThing).error(handleError);  
});
</script>
setTimeout(function() {
    // Second click
}, seconds * 1000);

Put your second click code in the setTimeout closure function

If all you want is a simple delay, I think jQuery can do this: https://api.jquery.com/delay/

jQuery('#sc_checkout_form_1').find('.sc-payment-btn').delay(1000).click();

Or use setTimeout as per other answers.

Just relying on a timeout / wait isn't a guarenteed solution however, see this answer: https://stackoverflow.com/a/32007018/15667

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