Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java

Getting the list of checked checkboxes! :)

In Spark, with Java I am doing a blog.

In a form, how can I get the checked values in a form where all the checkboxes share the same name?

I thought I would get a list of the values but somehow I am only getting the first one...

My html:

               <li th:if="${entry.tags}" th:each="tag,iterStat : ${entry.tags}">
                    <input
                            type="checkbox"
                            name="tags"
                            th:value="|tag-${iterStat.count}|"
                            th:checked="true"
                            th:text="${tag}">

                </li>

and in the controller I am doing:

String editedTags = request.queryParams("tags");

But I am only getting the value of the first checked one, only one...

I've read that I should get them with queryParams method as a String separated by commas...but that 's not the case, I am only receiving the first one

2 Answers

Seth Kroger
Seth Kroger
56,412 Points

The name attribute of each checkbox will need to be different if you want to send the values of each one of them. Otherwise with only one name there is only one value sent.

But the checkboxes are generated dinamically (one checkbox for each entry tag, and I do not know how many entry tags the user will enter)...

Isn't there to call all the checkboxes the same? after all, they are all the same: tags!

And I would swear I have seen it done just with one name...

Like here: https://www.w3schools.com/tags/tryit.asp?filename=tryhtml_form_checkbox

Seth Kroger
Seth Kroger
56,412 Points

OK, after a bit of research it looks like you should use queryParamsValues() instead of queryParams() since it returns an a String[] instead of a single String.