How to submit a form that will have a dynamic (unknown) number of fields
I am trying to submit a form to a servlet (java). The form has a bunch of questions, each question has 4 radio buttons and the user selects one of them. I do not know the number of questions that will be in the form. It could be 10, 15, 12 ... depends on some other criteria. My question is what is the best way to get a list of the choices the user has made for the questions on the form.
You can use HttpServletRequest.getParameterNames () to get an Enumeration of the names of all form elements in the request. Then you can iterate over the numbering and request an individual value for each item using HttpServletRequest.getParameter (name).
If your HTML contains other FORM elements than your radio buttons, use the smart naming convention for that radio button so that when you list the parameter names, you know what to ask for.
Example.
If your form contains two questions with the following parameters:
Question 1:
<input type="radio" name="question1" value="option1">
<input type="radio" name="question1" value="option2">
<input type="radio" name="question1" value="option3">
Question 2:
<input type="radio" name="question2" value="option1">
<input type="radio" name="question2" value="option2">
<input type="radio" name="question2" value="option3">
In your servlet
Enumeration e = request.getParameterValues();
while(e.hasMoreElements()){
String name = (String)e.nextElement();
if(name.startsWith("question"){
String value = request.getParameter(name);
//your logic here
}
}
Another example:
In your servlet
int maxQuestionNumber = Integer.parseInt (request.getParameter ("maxQuestionNumber")); // this should be a hidden variable in your HTML form representing the maximum questions on your form.
for(int i=1;i<=maxQuestionNumber;i++){
String value = request.getParameter("question"+i);
//your logic here..
}
a source to share
A quick trick that comes to my mind is to name all fields as
"question_"+n
And enter the input type hidden with the value n. If the form has a way to know how many questions to submit, it must have a way to set the value to n.
Later, you just extract that value and ...
n = new Integer( request.getParameter("number_of_question"));
for( int i = 0 ; i < n ; i++ ) {
list.add( request.getParameter("question_"+i));
}
This is the first thing that comes to my mind
a source to share
I would not suggest workarounds. ServletRequest.getParameterMap () comes in handy in this scenerio. Map keys will be of type String, and values will be of type String [].
Hence, you can loop through the map very easily using a foreach loop something like this,
for(Map.Entry<K, V> entry : map.entrySet()){
..
if(entry.getValue().length > 1){
//means the choices not the question
}else{
//means the question not the choices
}
}
I hope this helps.
a source to share