Varshini
Varshini

Reputation: 153

How do I make the first radio button option of a list of inputs selected by default on Shopify?

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.

Upvotes: 2

Views: 808

Answers (2)

Vladimir
Vladimir

Reputation: 2559

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 %}

Upvotes: 2

Anurag Srivastava
Anurag Srivastava

Reputation: 14423

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

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

Upvotes: 1

Related Questions