I made a product slider inside WooCommerce that displays the products and you can choose which category to display the products. By selecting the category, the products are changed using Ajax. Now my problem is that when the category is not selected, it means that the Ajax is not executed. You can select the product variables, i.e. product color and size, but after choosing the category that new products are added with Ajax, you can`t select the product variables.
html
<input type="hidden" name="variation_id" value="<?php echo $available_variations[0]['variation_id']; ?>">
<?php foreach ($variations as $key => $value): ?>
<div class="d-flex">
<div class="d-flex var_list">
<?php foreach ($value as $var): ?>
<div class="button-group">
<input type="radio" class="variation-attributes" name="attribute_<?php echo $key ?>" value="<?php echo $var; ?>" id="<?php echo $var; ?>-<?php echo $product_id ?>">
<?php if ($key === "pa_color"): ?>
<label style="background-color: <?php echo $color[$var] ?>; " class="variation-attributes pa_color" name="attribute_<?php echo $key ?>" id="<?php echo $var; ?>" for="<?php echo $var; ?>-<?php echo $product_id ?>"></label>
<?php else: ?>
<label class="variation-attributes" name="attribute_<?php echo $key ?>" id="<?php echo $var; ?>" for="<?php echo $var; ?>-<?php echo $product_id ?>"><?php echo $var; ?></label>
<?php endif; ?>
</div>
<?php endforeach; ?>
</div>
</div>
<?php endforeach; ?>
js
$(".variation-attributes").click(function () {
var label = $(this);
var input = label.siblings("input")[0];
input.checked = true;
let $forms = $(this).closest("form.cart");
const $variationsData = $forms.data("product_variations");
const $price = $forms.find(".price_variations");
const $variationIdInput = $forms.find('input[name="variation_id"]') || 0;
const $selectedTerms = $forms
.find(".variation-attributes:checked")
.map((idx, attr) => {
const attrObj = {};
attrObj[attr.name] = $(attr).val();
return attrObj;
})
.toArray();
const matchedVariation = $variationsData.find((variation) => {
return $selectedTerms.every((term) => {
const key = Object.keys(term)[0];
return variation.attributes[key] == term[key];
});
});
const variationId = matchedVariation.variation_id;
const priceHtml = matchedVariation.price_html;
$price.html(priceHtml);
$variationIdInput.val(variationId);
});
These are my codes that work before Ajax, but do not work after Ajax