Kimovi
Kimovi

Reputation: 45

HTML radio button is selecting multiple buttons although 'name' attribute has the same value

I googled for this, and the radio button should have the same 'name' attribute to allow only a single value to be chosen.

So I did, and It's still allowing me to choose multiple values... I used HTML and Jinja2 templates for this, so the code might be looking a bit strange..

   {% if search_keyword == None: %}
        <p>Please enter your search keyword</p>
    {% else: %}
        {% for i in range(0, 10) %}
        <form method="POST" action="./search">
          <h2>
              <input type="radio" name="selected_food" id="{{ i }}" value="{{ search_data["hits"][i]['recipe']['label'] }}">
              {{ search_data["hits"][i]['recipe']['label'] }}
          </h2>
          <h4>
              Calroies: {{ '%0.2f'| format(search_data["hits"][i]['recipe']['calories']) }} kcal
          </h4>
              {% for j in range(0, 40) %}
                <p>{{ search_data['hits'][i]['recipe']['ingredientLines'][j] }}</p>
              {% endfor %}
        </form>
        {% endfor %}
    {% endif %}

Upvotes: 0

Views: 118

Answers (1)

Rahul
Rahul

Reputation: 5844

In the above code the loop is creating multiple forms. This is the reason why you're able to select multiple values in radio.

If you can modify your code like this, it will work

{% if search_keyword == None: %}
        <p>Please enter your search keyword</p>
    {% else: %}
        <form method="POST" action="./search">
             {% for i in range(0, 10) %}
                <div>
                   <h2>
                       <input type="radio" name="selected_food" id="{{ i }}" value="{{ search_data["hits"][i]['recipe']['label'] }}">
                     {{ search_data["hits"][i]['recipe']['label'] }}
                   </h2>
                   <h4>
              Calroies: {{ '%0.2f'| format(search_data["hits"][i]['recipe']['calories']) }} kcal
                   </h4>
              {% for j in range(0, 40) %}
                <p>{{ search_data['hits'][i]['recipe']['ingredientLines'][j] }}</p>
              {% endfor %}

           </div>
            {% endfor %}
        </form>
     
    {% endif %}

Upvotes: 3

Related Questions