本文将详细介绍如何使用 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>
代码解释:
- document.querySelectorAll(‘input[type=”radio”]:checked’): 这行代码使用 querySelectorAll 方法选择所有 type=”radio” 且 checked 属性为 true 的元素。 换句话说,它会选择所有被选中的 Radio Button。
- Array.from(checkedRadios, radio => radio.value): 这行代码使用 Array.from 方法将 checkedRadios 这个 nodeList (类数组对象) 转换为一个真正的数组。 radio => radio.value 是一个箭头函数,它作为 Array.from 的第二个参数,用于指定如何将每个 Radio Button 元素转换为数组中的值。 在这里,我们提取每个选中 Radio Button 的 value 属性,并将其作为数组的元素。
注意事项:
- 确保每个 Radio Button 组都有一个 name 属性,且同一组的 Radio Button 的 name 属性值相同。
- variantsArray 变量需要在 JavaScript 代码中定义,并且包含产品变体的信息,例如 id 和 options。
- JSON.stringify 方法用于将数组转换为 JSON 字符串,以便进行比较。 如果 variantsArray[i].options 也是数组,则需要使用 JSON.stringify 将其转换为 JSON 字符串才能进行比较。
- 此代码假定 variantsArray 已经定义并包含了所有变体选项。请确保在实际应用中正确初始化和赋值 variantsArray。
总结
通过使用 querySelectorAll 和 Array.from 方法,我们可以轻松地获取不同 Radio Button 组的选中值,并将其存储在数组中。这种方法简单、高效,并且易于理解和维护。在实际开发中,可以根据具体需求进行适当的调整和扩展。
评论(已关闭)
评论已关闭