[英]store selected radio button values from different groups upon clicking a button
我正在为产品变体选项呈现不同的单选按钮组。 (例如:一件 T 恤可以有 3 个不同的单选按钮组:尺寸、材质、颜色)。 现在我正在尝试将用户选择的单选按钮值存储在一个数组中,并将产品变体添加到购物车中。 我在单选按钮上使用 onclick 事件存储值。 但正因为如此,如果我将尺寸选择从 XS 更改为 S,那么 XS 和 S 值都会添加到我的数组中。 但是我只需要将最终的单选按钮值存储在我的数组中,这样我就可以将它与我的 json 数据进行比较并找到变体 id。 因此,我试图将所有选定的单选按钮值存储为添加到购物车按钮上的 onclick 事件,这样它只会存储最终选定的单选按钮值。 但是,我不确定如何访问这部分中不同组的所有单选按钮值。 任何帮助将不胜感激。 到目前为止,这是我的代码:
<div class="radios">
{% for product_option in product.options_with_values %}
<p>{{ product_option.name }} -- </p>
{% for value in product_option.values %}
<input type="radio" id = "{{ value }}" name="{{ product_option.name}}" value="{{ value }}" >
<label for="{{ value }}">{{ value }}</label>
{% endfor %}
<br>
{% endfor %}
<script>
var optionsArray = [];
var filteredOptionsArray = [];
document.querySelector('.radios').addEventListener('click', function(e) {
optionsArray.push(e.target.value);
filteredOptionsArray = optionsArray.filter(function (el) {
return el != null;
});
console.log(filteredOptionsArray);
// console.log(optionsArray.toString());
})
</script>
</div>
<div class="quantity-add">
<div class="input-quantity">
<input class="input-quantity" type="number" min="1" placeholder="1" name="quantity" value="1">
<input type="hidden" id="add-cart" name="id" data-productid="{{ product.variants[0].id }}" value="{{ product.variants[0].id }}" data-variant-title="{{ product.variants[0].title }}" />
</div>
<div class="cart-button">
<button class="cart-btn" type="submit" value="Add To Cart">ADD</button>
<!-- script for adding the selected variant to the cart -->
<script>
document.querySelector('.cart-btn').addEventListener('click', function () {
for (let i=0; i < variantsArray.length; i++) {
if ((JSON.stringify(filteredOptionsArray))== (JSON.stringify(variantsArray[i].options))) {
console.log('stringify match check works');
console.log(variantsArray[i].options);
document.querySelector('#add-cart').value = variantsArray[i].id;
}
else {
console.log('stringify match check failed');
console.log(variantsArray[i].options);
}
}
})
</script>
</div>
找到它,我需要这样做:
const checkedRadios = document.querySelectorAll('input[type="radio"]:checked');
const radio_values = Array.from(checkedRadios, radio => radio.value);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.