Move Focus to WooCommerce Checkout Errors
When the classic WooCommerce checkout shows errors (such as a missing field or a declined card), moves keyboard focus to the error list and has screen readers read it out.
Opens WPIDE on
Code
<script>
jQuery(function ($) {
$(document.body).on('checkout_error', function () {
var box = document.querySelector('.woocommerce-NoticeGroup-checkout, .woocommerce-error');
if (!box) { return; }
box.setAttribute('tabindex', '-1');
box.setAttribute('role', 'alert');
setTimeout(function () { box.focus(); }, 100);
});
});
</script>
Notes
The block-based checkout handles this itself; this snippet is for the classic [woocommerce_checkout] shortcode checkout.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.