
本文将详细介绍如何使用 JavaScript 获取不同 Radio Button 组的选中值。正如摘要中所述,我们将使用 querySelectorAll 和 Array.from 方法来实现这一目标。这种方法不仅简洁明了,而且具有良好的浏览器兼容性,适用于各种 Web 开发场景。
原始代码尝试在每次 Radio Button 点击时存储值,导致重复和错误。正确的做法是在用户完成所有选择后,在“添加到购物车”按钮点击时一次性获取所有选中的值。
以下代码展示了如何在点击按钮时获取所有选中的 Radio Button 的值,并将其存储在数组中。
<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 }}">{{ value }}</label>
{% endfor %}
<br>
{% endfor %}
</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() {
const checkedRadios = document.querySelectorAll('input[type="radio"]:checked');
const radio_values = Array.from(checkedRadios, radio => radio.value);
console.log(radio_values); // 打印选中的 Radio Button 值数组
// 在这里进行后续处理,例如与 variantsArray 比较
for (let i = 0; i < variantsArray.length; i++) {
if ((JSON.stringify(radio_values)) == (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>
</div>代码解释:
注意事项:
通过使用 querySelectorAll 和 Array.from 方法,我们可以轻松地获取不同 Radio Button 组的选中值,并将其存储在数组中。这种方法简单、高效,并且易于理解和维护。在实际开发中,可以根据具体需求进行适当的调整和扩展。
以上就是获取不同 Radio Button 组的选中值:专业教程的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号