Chi*_*ana 5 wordpress jquery woocommerce
在可变产品页面上,当您单击“添加到购物车”而不选择任何属性时,它会向您显示类似这样的警报
因此,我想显示一条消息,表示未选择特定属性或未选择一组属性,而不是显示此警报。
例如,
Please select a color.Please select a color and size.我尝试过使用 jQuery 来实现的解决方法
$('.single_add_to_cart_button').on('click', function (e) {
if ($(this).is('.disabled')) {
e.preventDefault();
if ($(this).is('.wc-variation-selection-needed')) {
var empty_variations = [];
$('form.variations_form.cart').find('table.variations tr').each(function( index ) {
var $variation_label = $(this).find('td.label');
var $variation_value = $(this).find('td.value');
var $variation_dd = $('select', $variation_value);
if( $variation_dd.val() == '' || $variation_dd.val() == null ){
var label_text = $('label', $variation_label).text();
empty_variations.push( label_text )
}
});
if( empty_variations.length != 0 ){
alert( 'Please select ' + empty_variations.join(', ') + '.');
return false;
}
}
}
});
Run Code Online (Sandbox Code Playgroud)
但是任何人都可以让我知道实现此目的的标准方法。
谢谢!
不幸的是,没有可用的 WooCommerce 挂钩可用于修改在未选择所需属性时出现的警报通知的默认操作。
与在将产品添加到购物车之前验证产品属性相关的挂钩是woocommerce_add_to_cart_validation. 但不适用于修改警报消息。
因此,使用jQuery捕获“添加到购物车”按钮的点击事件并显示自定义错误消息是实现需求的最佳方式。
问题中给出的代码不起作用,并且给出了这个结果(是的,我jQuery( document ).ready()在 Woo-Commerce 版本 7.5.1,店面主题版本:4.2.0 中使用它)。因此,我做了一些更改以使其正常工作,这是我的 jQuery 代码:
jQuery(document).ready(function ($) {
// Find the add to cart button
const addToCartButton = $('button.single_add_to_cart_button');
// Override the default WooCommerce behavior
addToCartButton.on('click', function (event) {
if ($(this).is('.disabled.wc-variation-selection-needed')) {
// Find all the attribute selectors
const attributeSelectors = $('.variations select');
// Check if any of them have not been selected
const missingAttributes = attributeSelectors.toArray().filter(function (selector) {
return selector.value === '';
}).map(function (selector) {
return $(selector).parent(".value").siblings(".label").children('label').text().replace(/[:\n]/g, '').trim();
});
// If any attribute has not been selected, prevent default behavior and show custom alert
if (missingAttributes.length > 0) {
event.preventDefault();
alert('Please select the following product options: ' + missingAttributes.join(', ') + '.');
return false;
}
}
});
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
331 次 |
| 最近记录: |