Dynamic textbox and its value submission in JSP bean

I have a form with few predefined textboxes, now in addition to that I have create some dynamic textboxes which I can do it in javascript(I guess). How do I set the value of dynamically generated textboxes to a bean when the form is submitted. In the bean I have string array defined to hold the content of dynamically generated textbox values. I am not using any framework, guide me how to do this ?

Answer

You can just give all input fields the same name and use request.getParameterValues() to get all values in order as they appeared in the HTML DOM tree.

E.g. (JavaScript-generated)

<input type="text" name="foo" />
<input type="text" name="foo" />
<input type="text" name="foo" />
...

with

String[] values = request.getParameterValues("foo");
// ...

You can also suffix the name with an incremental digit such as foo1, foo2, foo3, etc and collect the values in a loop with until a null is received.

E.g.

<input type="text" name="foo1" />
<input type="text" name="foo2" />
<input type="text" name="foo3" />
...

with

List<String> foos = new ArrayList<String>();

for (int i = 1; i < Integer.MAX_VALUE; i++) {
    String foo = request.getParameter("foo" + i);
    if (foo == null) break;
    foos.add(foo);
}

// ...

Leave a Reply

Your email address will not be published. Required fields are marked *