How to add checked attribute to input conditionally in Thymeleaf

January 18, 2020 No comments Thymeleaf Checkbox Conditional QA

1. Introduction

Thymeleaf is a featured template engine for processing HTML documents widely used by web developers in Spring Boot applications. The engine uses simple XML attributes that cover almost all HTML5 attributes and adds many more. In this short article, we are going to present how to conditionally check checkboxes in Thymeleaf forms.

2. Using th:checked attribute

Thymeleaf attributes accept not only simple primitive variables but any expression that could be evaluated by the engine. We can dynamically control what will be rendered on the output website.

th:checked attribute is a Thymeleaf representation of checked attribute in HTML documents used for checkboxes. It accepts Boolean variables or methods that return Boolean values.

To present how th:checked attribute works we prepare a simple application with the following controller class:

package com.frontbackend.thymeleaf.bootstrap.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import lombok.Builder;
import lombok.Getter;

public class IndexController {

    public String main(Model model) {
        model.addAttribute("flag", true);
        model.addAttribute("customer", Customer.builder()
        return "index";

    private class Customer {
        private Boolean active;
        private String name;

In our template we will use flag variable and attribute to set initial value of checboxes on the form:

<html lang="en" xmlns:th="">
    <meta charset="UTF-8"/>
    <title>Spring Boot Thymeleaf Application - Checkbox Checked Conditionally</title>

<div class="container">

    <div class="row">
        <div class="col">
            <form method="post">

                    <input type="checkbox" th:checked="${flag}"/> Flag

                    <input type="checkbox" th:checked="${customer.getActive()}"/> Customer active

                    <input type="checkbox" th:checked="${flag ? false: true}"/> Flag negation



3. Conclusion

In this article, we presented how to conditionally checked checkboxes in Thymeleaf templates. Thymeleaf engine evaluates the expression in the dedicated attributes so we can easily control components using Java objects.

{{ message }}

{{ 'Comments are closed.' | trans }}