0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

[ひとくちThymeleaf Tips] th:disabled disabledプロパティの適用

Last updated at Posted at 2024-04-21

ひとくちThymeleaf Tips disabledプロパティの適用

「Thymeleafってこんな機能があるんだ」という気分になってくれたらいいなという、Thymeleafの機能について一口サイズで紹介させていただく記事です。

非活性のステータスにするth:disabled

htmlの標準機能にある「disabled」を条件付きで指定できるthタグです。
通常のhtmlだと「disabled」の付与自体は可能なのですが、動的に「disabled」する/しないを切り替えるためにはjavaScriptなど外部からの制御が必要。
基本的に「活性/非活性」はセットで動的に切り替えられるように作るはずなので、そんな時に便利なthタグです。

記法

以下の{条件式}がtrueの場合のみ、「disabled」が適用されます。

th:disabled="{条件式}"

使用例

htmlに紐づけてあるFormオブジェクト「doClick(boolean型)」のステータスを見て、disabledを切り替える例です。
htmlヘッダなど細かい部分は割愛します。
「doClick」がfalseの場合のみボタンにdiabledが適用されます。「クリックし手非活性に」ボタンを押下すると「doClick」にfalseが設定されるように記載。

Hello.html
<body>
	<h1>Hello World</h1>
		
	<form method="post" action="/hello/post" th:object="${helloForm}">
		<span th:text="*{demoText}"></span>
		<input type="submit" value="クリックして非活性に" th:disabled="*{doClick == false}">
	</form>
</body>
DemoController.java
@Controller
@RequestMapping("/hello")
public class DemoController {

	
	@GetMapping
	public String getHello(Model model,@ModelAttribute HelloForm form) {
		String url="demo/hello.html";
		
		form.setDemoText("ステータス切り替え前");
		form.setDoClick(true);
		
		return url;
	}
	
	@PostMapping("post")
	public String getPost(Model model,@ModelAttribute HelloForm form) {
		String url="demo/hello.html";

		form.setDemoText("ステータス切り替え後");
		form.setDoClick(false);
		return url;		
	}
}
HelloForm.java
@Data
public class HelloForm {
	
	private String demoText;
	
	private boolean doClick;

}

画面起動して確認

ボタン押下前
スクリーンショット 2024-04-21 180532.png

ボタン押下後
スクリーンショット 2024-04-21 184700.png

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?