Ruby on Rails — Nested radio buttons issue (When one is selected other is deselected)

Multi tool use
Ruby on Rails — Nested radio buttons issue (When one is selected other is deselected)
So I have a form in which each question has different options and one of the options in each question needs to be selected:
<% @exam.exam_questions.each do |question|%>
Question: /
</div>
</div>
<br />
<br />
<%= hidden_field_tag :exam_answer_exam_question_id, question.id, :name => "exam_answers[exam_question_id]"%>
<%= hidden_field_tag :exam_answer_student_id, current_student.id, :name => "exam_answers[student_id]"%>
<%= hidden_field_tag :exam_answer_exam_id, question.exam_id, :name => "exam_answers[exam_id]"%>
<% end %>
Suppose I select an option from one question( radio button ), when I move on to the next question and select another option the option I selected from the previous question becomes unselected. Can anyone tell em how to fix that?
1 Answer
1
Your issue is using the same name for each set of radio buttons (exam_answers[answer_mcq]
).
exam_answers[answer_mcq]
If you update your code to use each_with_index
or the question's ID (or whatever you like really) and add this on to the radio_button_tag
name, this will work for you.
each_with_index
radio_button_tag
For example:
<% @exam.exam_questions.each_with_index do |question, i|%>
...
<%= radio_button_tag :exam_answer_answer_mcq, option_position_to_answer(question.options.split(',').find_index(option)), false, :name => "exam_answers[answer_mcq_#{i}]"%>
...
<% end %>
Or:
<%= radio_button_tag "exam_answer_answer_mcq_#{i}", option_position_to_answer(question.options.split(',').find_index(option)), false, :name => "exam_answers[answer_mcq_#{question.id}]"%>
Using the same name groups all the options together, meaning only one can be selected per group. Updating to use an approach as above will overcome this by differentiating the groups.
Hope that helps - let me know how you get on or if you have any questions.
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.