Shopify默认选择第一个可用变体的单选按钮



我正在从头开始开发一个主题,我正面临一个问题,我正在将产品选项呈现为单选按钮组。当用户选择或更改单选按钮时,我将相应地更新价格。我的问题是,我不知道如何选择第一个可用的变体作为所选的单选按钮值。我这样做的方式是,当页面加载时,最后一个可用的变体作为默认选择的单选按钮。

任何帮助都将非常感激。下面是我的代码:

<!-- storing the variants in json form -->
<script id="variants" type="application/json">
{{ product.variants | json }}
</script>
<!-- creating an array from the json data-->
<script>
var variantsArray= JSON.parse(document.getElementById("variants").text);
console.log(variantsArray);
</script>
<span class="unit-price">{{ price | money }}</span>
<!-- rendering the radio button groups -->
<div class="radios">
{% for product_option in product.options_with_values %} 
<h4 class="options-title">{{ product_option.name }}</h4>
<div class="options-values">
{% for value in product_option.values %}
<input type="radio" id = "{{ value }}" name="{{ product_option.name}}" value="{{ value }}" checked >
<label for="{{ value }}">{{ value }}</label>  
{% endfor %}
</div>
<div class="line"></div>
{% endfor %}
<!-- script for updating the price on variant change -->
<script>
var radioArray = document.querySelectorAll('input[type="radio"]');
var checkedArray = [];
for (let k=0; k<radioArray.length; k++) {
radioArray[k].addEventListener('change', function () {
var checkedValues = document.querySelectorAll('input[type="radio"]:checked');
checkedArray = Array.from(checkedValues, radio => radio.value);
console.log(checkedArray);

for (let l=0; l < variantsArray.length; l++) {
//if the variant selection matches the json variant options then update the price
if ((JSON.stringify(checkedArray))== (JSON.stringify(variantsArray[l].options))) {
//formatting the price manually (need to fix later)
var priceString = variantsArray[l].price.toString();
document.querySelector('.unit-price').textContent = `$${priceString.substr(0,priceString.length-2)}`;
}
}
})  
}  
</script>
</div>

我需要在单选按钮中添加一个if条件。

{% for value in product_option.values %}
<input type="radio" id = "{{ value }}" name="{{ product_option.name}}" 
value="{{ value }}" {% if forloop.index == 1 %} checked="checked" {% endif %}>
<label for="{{ value }}">{{ value }}</label>  
{% endfor %}