views:

210

answers:

3

I am dynamically naming a set of checkboxes based on certain files names (user is selecting file to include for some processing).

Is there a way I can retrieve the files names or do I need to save them to a session object of some sort and then use the retrieved values (from the session object) to retrieve the values of the checkboxes.

In short what I really want is to know which checkboxes have been clicked and which file names they correspond to, any solution will be fine.

+5  A: 

Use unique id, but same name. Then you will be able to use either getParameterValues(name), or getParameterMap() of ServletRequest. Remember, you will only get what is selected.

Adeel Ansari
This was my immediate response, too. You beat me to it.
Paul Hanbury
Indeed just give them all the same `name` and access them using `getParameterValues()`. There's no need for the brace notation as some PHP'er noticed here by the way.
BalusC
In the end I refactored the code and used the reParameterValues() method to get a list of the selected checkboxes. That's all I need for the rest of the code to work, so all is good. Thanks.
Ankur
A: 

Are you doing all this server side or using java-script client side?

If it's all server side, why not prepend checkbox on the name when you dynamically name them:

<input type="checkbox" name="checkbox_someRandomeName" value="something" />

You can then loop the posted variables and see if the name starts with "checkbox":

ParameterMap paramMap = request.getParameterMap();
// Loop through the list of parameters.
Iterator y = paramMap.keySet().iterator();
while (y.hasNext()) {
  String name = (String) y.next();  
  if name.startswith("checkbox"){
    // do something
  }
}
Mark
That's an interesting idea, but the above technique as Vinegar has suggested.
Ankur
Ahh, makes perfect sense. I assumed you were using the name and the value properties to both store variable information, so therefore you needed to keep your naming structure intact.
Mark
A: 

What does your HTML look like? I'd expect checkboxes like:

<li><input id='0001' type='checkbox' name="files[]" value="file1"/>/xyz/file1</li>
<li><input id='0002' type='checkbox' name="files[]" value="file2"/>/xyz/file2</li>
<li><input id='0003' type='checkbox' name="files[]" value="file3"/>/xyz/file3</li>
<li><input id='0004' type='checkbox' name="files[]" value="file4"/>/xyz/file4</li>

The name will be associated with any values checked on submit. Here, I used files[] because that's required by PHP, I haven't done this in servlets.

NVRAM