Vinicius Santana Vinicius Santana - 3 months ago 23
Javascript Question

How to make first radio button selected by default in a list built with a for in loop using twig?

I'm using twig to make a list of radio buttons with Database values. It's something like:

{% for usermembershiptype in usermembershiptypes %}
<div class="ms_type noline">
<p>{{ usermembershiptype.description}}</p>
<label class="ms_price ms_odd">${{ usermembershiptype.price }}<span>/year</span><input name="membership-type" type="radio" value="{{ usermembershiptype.id }}"/></label>
<div class="clearfix"></div>
</div>
{% endfor %}


I want the first radio button to be selected by default but when using a for in loop, I'm not sure about how to refer to the first radio button.

Any advices? Javascript and Jquery Solutions are also welcome.

Answer

You can use the loop.index and if condition like

{% for usermembershiptype in usermembershiptypes %}
    <div class="ms_type noline">
        <p>{{ usermembershiptype.description}}</p>
        <label class="ms_price ms_odd">${{ usermembershiptype.price }}<span>/year</span>
            {% if loop.index == 1 %}
                <input name="membership-type" type="radio" value="{{ usermembershiptype.id }}" checked/>
            {% else %}
                <input name="membership-type" type="radio" value="{{ usermembershiptype.id }}"/>
            {% endif %}
        </label>
        <div class="clearfix"></div>
    </div>
{% endfor %}

Note: not tested


Using loop.first

{% for usermembershiptype in usermembershiptypes %}
    <div class="ms_type noline">
        <p>{{ usermembershiptype.description}}</p>
        <label class="ms_price ms_odd">${{ usermembershiptype.price }}<span>/year</span>
            {% if loop.first %}
                <input name="membership-type" type="radio" value="{{ usermembershiptype.id }}" checked/>
            {% else %}
                <input name="membership-type" type="radio" value="{{ usermembershiptype.id }}"/>
            {% endif %}
        </label>
        <div class="clearfix"></div>
    </div>
{% endfor %}