Thymeleafでラジオボタン(radio)の選択値に応じて連動させる方法

Thymeleafでラジオボタン(radio)の選択値に応じて連動させる方法

Thymeleafでラジオボタンの選択値に応じて連動させる方法を説明します。
ここでは、ラジオボタンの選択に応じて他のフォーム要素の内容を変更する例を示します。

1. HTMLテンプレート (Thymeleaf)

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
  <title>ラジオボタンの連動</title>
</head>
<body>
  <form th:action="@{/processForm}" method="post" th:object="${form}">
    <div>
      <label>
        <input type="radio" th:field="*{radioOption}" value="option1" />
        オプション 1
      </label>
      <label>
        <input type="radio" th:field="*{radioOption}" value="option2" />
        オプション 2
      </label>
    </div>

    <div th:if="${form.radioOption == 'option1'}">
      <label for="text1">オプション 1 用テキスト:</label>
      <input type="text" id="text1" th:field="*{textOption1}" />
    </div>

    <div th:if="${form.radioOption == 'option2'}">
      <label for="text2">オプション 2 用テキスト:</label>
      <input type="text" id="text2" th:field="*{textOption2}" />
    </div>

    <button type="submit">送信</button>
  </form>
</body>
</html>

2. コントローラ (SpringBoot)

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

@Controller
@RequestMapping("/form")
public class FormController {

  @GetMapping
  public String showForm(Model model) {
    model.addAttribute("form", new Form());
    return "form";
  }

  @PostMapping("/processForm")
  public String processForm(@ModelAttribute Form form, Model model) {
    // フォームの内容を処理
    model.addAttribute("form", form);
    return "result"; // 処理結果を表示するテンプレート
  }
}

3. フォームクラス (Java)

public class Form {

  private String radioOption;
  private String textOption1;
  private String textOption2;

  // ゲッターとセッター

  public String getRadioOption() {
    return radioOption;
  }

  public void setRadioOption(String radioOption) {
    this.radioOption = radioOption;
  }

  public String getTextOption1() {
    return textOption1;
  }

  public void setTextOption1(String textOption1) {
    this.textOption1 = textOption1;
  }

  public String getTextOption2() {
    return textOption2;
  }

  public void setTextOption2(String textOption2) {
    this.textOption2 = textOption2;
  }
}

この例では、ラジオボタンの選択に応じて表示するテキストボックスを切り替えています。
ラジオボタンの値がoption1の場合、textOption1用のテキストボックスが表示され、option2の場合はtextOption2用のテキストボックスが表示されます。