How do I keypress the key enter to submit my coupon code in mobile and desktop? Keypress enter is not working, I have to click the submit button so the coupon code will apply. Did I make some mistake?
JQUERY
$(document).ready(function() {
testKey();
});
function testKey() {
$("#inputbox").keypress(function(event) {
if (event.which == 13) {
event.preventDefault();
$(this).closest("form").submit();
}
});
}
PHP
<form id="testt" action="<?php echo esc_url( WC()->cart->get_cart_url() ); ?>" method="post">
<?php do_action( 'woocommerce_before_cart_table' ); ?>
<div class="coupon">
<?php if ( WC()->cart->coupons_enabled() ) { ?>
<span for="coupon_code"><?php _e( 'Coupon code:', 'woocommerce' ); ?></span>
<div class="input-container">
<div class="form-row">
<input id="inputbox" class="input" type="text" name="coupon_code" value="" placeholder="<?php esc_attr_e( 'bebrave', 'woocommerce' ); ?>" />
</div>
<input type="submit" class="ds btn" name="apply_coupon" value="<?php esc_attr_e( 'Apply Coupon', 'woocommerce' ); ?>" />
<?php do_action( 'woocommerce_cart_coupon' ); ?>
</div>
<?php } ?>
<?php wc_print_notices(); ?>
<?php do_action( 'woocommerce_cart_actions' ); ?>
<?php wp_nonce_field( 'woocommerce-cart' ); ?>
</div>
<?php do_action( 'woocommerce_after_cart_contents' ); ?>
<?php do_action( 'woocommerce_after_cart_table' ); ?>
</form>
If you want submit your form using the Enter key, use something like :
$(document).ready(function() {
$('#inputbox').keypress(function(e) {
e.preventDefault();
if (e.keyCode == 13) {
$('#testt').submit();
}
});
});
To listen on the keypress event, out of any function. If you are focus on the #inputbox input, the logic inside the condition will be called.
EDIT
It's just perfectly working.
I have made a fiddle for you, that call the on-submit event of your form on hit enter in your #inputbox :
How about simulating clicking the submit button when pressing Enter in the text box ? try something like
$("#inputbox").keypress(function(event) {
if (event.which == 13) {
event.preventDefault();
$(this).closest('input[type=submit]').click();
}
});