skip to Main Content

I’m creating a Shopify theme in which product options are made of radio buttons rather than dropdown selects. For example, the code for the product color option is:

{% for value in option.values %}
  {% assign radio_id = 'option-' | append: option_name | append: '-' | append: value | handleize %}
  <input class="variant-radio" id="{{ radio_id }}" type="radio" name="{{ option_name }}" value="{{ value }}" {% if value == selected %}checked{% endif %}>
  <label for="{{ radio_id }}">
    {{ value }}
  </label>
{% endfor %}

How do I make the first option as the default selected color? If I remove the {% if value == selected %} and {% endif %} around checked, it only sets the last option as selected by default.

2

Answers


  1. You can omit the if value == selected code and use jquery:

    $("input[type=radio].variant-radio:first").attr('checked', true);

    Login or Signup to reply.
  2. You can use {% forloop.index %} to get the current index of your cycle from within the “for” loop.

    So you can use something like that:

    {% for value in option.values %}
      ...
      <input type="radio"{% if forloop.index == 1 %} checked="checked"{% endif %}>
      ...
    {% endfor %}
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search