0

I have a multiple select something like this..

<select multiple="multiple" th:field="*{names}">
 <option value="abc">abc</option>
 <option value="def">def</option>
 <option value="ghi">ghi</option>
 <option value="jkl">jkl</option>
</select>

where names is the name of the list which looks like this..

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

Now, I would like the user to select multiple names and then put into the names list. Consider that I have selected

  1. abc

  2. def

  3. ghi

When I am submitting the form, I see that the data is sent like this..

names=abc&names=def&names=ghi

however, I want it to be like names[0]=abc&names[1]=def&names[2]=ghi.

P.S. I don't want to use Ajax form sending.

JavaTechnical
  • 8,846
  • 8
  • 61
  • 97

1 Answers1

0

Why is it important to have the submitted form's query string look a certain way? Is it because you are processing this form with a different framework other than Spring MVC?

Based on your tags of spring-mvc, Spring expects the names=abc&names=def&names=ghi. That is the data for the names <select> form field, which is a single form field with multiple values. Internally, Spring will correctly map it to the names property for a form-backing bean.

To get names[0]=abc&names[1]=def&names[2]=ghi, you will need 3 <select> elements in your HTML to represent each unique field name (i.e. names[0], names[1], etc), which is something I doubt you want.

As far as I know, that's the behavior of HTML and can't be changed.

I also did a quick search and was reminded that PHP requires the name of multi-select fields to end in [] for it to be parsed as an array. But that's a PHP-only quirk. That's the closest reason I can think for your original requirement. However, that would have required something like this instead: names[]=abc&names[]=def&names[]=ghi. And I doubt you can mimic that with Spring/Thymeleaf since those are not valid property name characters. See this for details: https://stackoverflow.com/a/11616681/1034436 (noting the comments)

Community
  • 1
  • 1
martian111
  • 595
  • 1
  • 6
  • 21