This tutorial series focuses on using Thymeleaf templates for Spring web applications.

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.

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.

Satish Pandey

I am an expert Java Spring Angular developer with 10+ years of rich and varied experience in developing end-to-end Web Applications.
I maintain this blog and publish articles in my free time to help the community.
Email: satish@cloudtechpro.com

Leave a Reply

1024

This comment form is under antispam protection

1024

This comment form is under antispam protection

Subscribe

Notify of

About Author

Satish Pandey

I am an expert Java Spring Angular developer with 10+ years of rich and varied experience in developing end-to-end Web Applications.

I maintain this blog and publish articles in my free time to help the community.