Reputation: 627
I have a list of 50 questions and request the user to answer any 25 questions of his choice. I am using JSP and Servlet for this purpose.
Here is my code:
<form action="Servlet1" method="post">
<%List questions = new ArrayList(); // This list has 50 questions
for(int i=1; i<questions.size(); i++)
{ %>
Question Number: <% out.println(i); %><br><br>
<%=questions.get(i)%><br><br>
Answer:
<input type="hidden" name="question" value="<%=questions.get(i) %>">
<input type="text" name="answer"> <br><br>
<input type="submit" value="submit" name="submit">
<% } %>
But in Servlet when I use request.getParameter("answer");
it gives me answer for only the recent question which is displayed, When the user answers some other question..it gets saved as blank (not "null" it get saved as " "-empty space) Also the question is also not getting saved accordingly. But when the user answers the recent question, both the question and answer gets saved..
I think its because some logic error..can anyone help me with a solution...
I want to save the question and answer in the database, whichever questions user answers..
Upvotes: 1
Views: 78
Reputation: 1
Put submit button out side the loop it will send all filed value to your Servelt
Upvotes: 0
Reputation: 437
It is because you can not have same name with multiple input type . try appending some alias after your input name Like shwon below:
<input type="text" name="answer_<%=i>"> <br><br>
Upvotes: 2
Reputation: 7630
In the html, each element is identify either by name or id. but it must be unique.
This code do loop on questions and it's everytime define same name which is answer
for text input.
so it will not create another one but override previous one text.
Thus you have to use either i
else another approach to make it unique like
<input type="text" name="answer<%=i>"> <br><br>
you can get at server side like
for(int i=1; i<questions.size(); i++)
{
String answer= request.getParameter("answer"+i)
//add logic here
}
I hope this will help!!
Upvotes: 3