Java Servlet: How can I retrieve selected radio button values?
java, radio-button, servlets
Solution
You have to define the value you want to retrieve when the radio button is selected
The value setting defines what will be submitted if checked.
The name setting tells which group of radio buttons the field belongs to. When you select one button, all other buttons in the same group are unselected.
<input type="radio" name="Q2" onclick="getAnswer('b')" value="b">
<input type="radio" name="Q2" onclick="getAnswer('a')" value="a">
In your Servlet which will recieve the request you'll have something like
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// get the value of the button group
String q2 = request.getParameter("Q2");
// compare selected value
if ("a".equals(q2)) {
...
}
...
}
Problem
I have created a simple servlet in which a user will be presented with 2 questions, answering either true or false. My problem lies in retrieving the answers selected by the user. Code: ``` out.println("<FORM ACTION=\"Game\" METHOD = \"POST\">" + "<b>Question 1: Are you over the age of 25? </b><br> <br>" + "<input type = \"radio\" name = \"Q1rad1\" onclick = \"getAnswer('a')\"> True " + "<input type = \"radio\" name = \"Q1rad2\" onclick = \"getAnswer('b')\"> False<br>" + "<br><br><b>Question 2: Are you from earth?</b><br> <br>" + "<input type = \"radio\" name = \"Q2rad1\" onclick = \"getAnswer('a')\"> True " + "<input type = \"radio\" name = \"Q2rad2\" onclick = \"getAnswer('b')\"> False<br>" + out.println("<Center><INPUT TYPE=\"SUBMIT\"></Center>"); ); ``` Each question has 2 radio buttons, Q1rad1 & Q2rad2, for answering True or False. How can i know the value selected by each user when the submit button is pressed. I understand it may be more efficient when using Javascript but for the purposes of this problem I must be using servlets.