OOPs way of Handling Radio Buttons using Thymeleaf

1. Introduction

In this tutorial, we will learn how to display/submit radio buttons in Thymeleaf by Object Oriented Programming approach. We will create a model object that will be used by input form and finally submit it back to Spring Controller.

2. Radio button group problem

Let’s assume you have a list of elements in a model object and you want to populate a group of radio buttons using Thymeleaf th:field tag. Now, if you iterate using th:each and create elements, Thymeleaf will produce a different name and id for every aspect. In that case, radio buttons will not work as a group, but all of them are independent.

3. Solution

Because we need to follow OOPs approach to solve the problem, we must not change the model object and collection. We also must use th:field to populate fields so that during input form submission actual item from the list would get updated automatically.

Now we can apply some JavaScript function that will control the radio buttons and group them. Let’s see a practical example.

4. Prepare Model Attribute

Let’s create a new entity that will hold the data required by a single radio box.

public class Month {

    private String name;
    private Boolean checked;

    // setters and getters


Next, we need to prepare a Model class that will contain a list of Month.

public class MonthGroup {

    private List<Month> months = new ArrayList<>();

    // setters and getters


Finally, we need to add MonthGroup object to Spring Model View.

modelAndView.addObject("monthGroup", new MonthGroup());

5. Prepare HTML Input Form

5.1. Preparing input form

Let’s create a new input form with MonthGroup model object.The input form will display the list of the month and contains unique names per radio button.

<form th:object="${monthGroup}" th:action="@{/radiobox-submit}" method="post">
  <div th:each="month, stat: ${monthGroup.months}">
    <input type="radio" th:field="*{months[__${stat.index}__].checked}" value="true" th:text="${month.name}">
  <input type="submit" value="Submit">

5.2. Include JavaScript

Now, our input form is ready to process requests back to the controller, but users can select multiple radio buttons because their names are unique. Let’s write some JavaScript code to prevent users selecting multiple radio buttons.

        function (e) {
                function () {
                        .prop('checked', false);

Now we are done with all steps, and now we can deploy and run the application.

6. Conclusion

In this tutorial, we have learned how to handle an HTML input form with radio buttons using Thymeleaf by following OOPs approach.

The complete source can be found over on GitHub.

Leave a Reply

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