LoginSignup
5
4

More than 5 years have passed since last update.

一列でチェックボックスを表示する

Posted at

目的

  • 以下のように横一列に表示されるチェックボックスを設置する
  • チェックボックスの項目はcontrollerから表示し、ベタで書かない

手順

チェックボックスの項目をControllerに定義する

Controller
@ModelAttribute("sortOptions")
    public List<String> sortChecboxList() {
        List<String> list = new ArrayList<String>();
        list.add("案件区分");
        list.add("金額");
        list.add("リース会社名");
        list.add("検収");
        list.add("入金");
        list.add("ステータス");
        return list;
    }
  • ModelAttributeを指定し、リクエスト時にsortOptionsと定義されたリストオブジェクトをリクエストスコープへ登録する

  • mapなどを使った方が、区分値をcontrollerを渡せるためいいと思われる、後日追記する

チェックボックスの入力値を受け取るフォームのフィールド

Form
    private String[] checkedBox;
  • チェックボックスからの値は、配列で戻されてくるため、配列でfieldを用意する

テンプレート上での定義

template
<div class="checkbox-inline" th:each="sort : ${sortOptions}">
    <label> <input type="checkbox" name="fchecks" th:value="${sort}" th:text="${sort}" th:field="*{checkedBox}">checkbox</input>
    </label>
</div>

値の受け渡し

  • th:eachでリクエストスコープから先ほどコントローラでModelAttributeで登録した表示項目を取得し、sort変数へリストをループしながら渡す
  • th:textへsort変数を渡すと、そのループ時の内容が表示される
  • チェックをクリックした時の値をコントローラへ渡すには、formクラスで定義したフィールド名をth:field属性に渡す th:field="*{checkedBox}"
  • これにより、チェックされた値が、checkedBox変数へ配列で格納された状態でcontrollerへ受け渡される

横一列に並べる

  • 項目ごとに改行される通常のチェックボックスの定義は以下であるが、
template
<div class="checkbox" th:each="sort : ${sortOptions}">
  • class属性に -inline オプションを以下のように追加する
template
<div class="checkbox-inline" th:each="sort : ${sortOptions}">
5
4
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
5
4