Search code examples
htmldjangofor-loopradio-button

Radio buttons in for loop only allows one selection for all iterations


I am working on building an attendance submission form (pictured below) in Django, but I am not currently using the Django Forms. I am having an issue with the radio buttons allowing only one selection for all iterations of the for loop.

In the HTML, it loops through a list of students and within each of those iterations, it loops through a list of attendance types. Each attendance type is represented by a radio button because only one attendance type should be able to be chosen. However, this only allows one option to be selected for the whole for loop, instead of allowing one option to be chosen for each student.

{% for student in list_of_students %}
    <tr>
        <td>{{student}}</td>
        <td>
            {% for attendanceType in list_of_attendanceTypes %}
                <input type="radio" name="attendancetype" id={{attendanceType}} value={{attendanceType.attendancetypeid}}>
                <label for={{attendanceType}}> {{attendanceType}}</label><br>
            {% endfor %}
        </td>
    <tr>
{% endfor %}

Is there a way to do this without changing the name of the buttons in each iteration of the for loop?

Any help would be appreciated.


Solution

  • The reason why you can only select one option over all radio button is because all radio buttons has the same name "attendancetype", try having different radio button group names, ex. "attendancetype_studentA" for each students :)

    {% for student in list_of_students %}
        <tr>
            <td>{{student}}</td>
            <td>
                {% for attendanceType in list_of_attendanceTypes %}
                    <input type="radio" name='{{student}}_attendance' id={{attendanceType}} value={{attendanceType.attendancetypeid}}>
                    <label for={{attendanceType}}> {{attendanceType}}</label><br>
                {% endfor %}
            </td>
        <tr>
    {% endfor %}