0
0

【jQuery】 DataTablesでnullとrenderオプションを使って、複数のフィールドの値を組み合わせて表示する方法

Posted at

概要

jQueryのDataTablesのrenderオプションを使用して、複数のフィールドを連携して表示するよう実装しました。使い方について説明します。

サンプルコード

以下のようにrender関数を使用して、condition1condition2condition3の値を連結して表示することができます。
dataにはバックエンド側からデータが連携される前提です(私はdjangoを利用しました)。

$(document).ready(function () {
    var RenderTable = function (data) {
        var table = $('#sample_table').DataTable({
            "language": {
                "url": "//cdn.datatables.net/plug-ins/3cfcc339e89/i18n/Japanese.json"
            },
            //  略 
            data: data,
            columns: [
                {
                    "data": null,
                    "title": '連結名',
                    "render": function (data, type, row) {
                        return row.condition1 + ' ' +
                               row.condition2 + ' ' +
                               row.condition3;
                    }
                },
                //  略 

ポイントは、"data": null:を設定することによって、render関数内でrowオブジェクト全体にアクセスできるようになり、また値を自由にカスタマイズできること。nullになっているので、特定のキーに依存せず、この関数内で自由にデータを組み合わせて表示することができるようになるのです。

公式ドキュメントにも以下のように記載されています。

Functions
Using columns.render is the most common method as it provides absolute control over the data that will be displayed to the end user (this is a regular Javascript function, so you can do virtually anything you wish with the data).

The function is passed in three parameters:

  1. The data that is pointed to by columns.data. If columns.data is null, null will be the value given here.
  2. The data type being requested by DataTables - this allows the function to support orthogonal data.
  3. The original and full data object or array for the row.

If columns.data is null, null will be the value given here.」と記載されているように、nullとしておけばrenderの結果が入るようになっています。

上記のようにすることで、複数のフィールドの値を組み合わせて1つのセルに表示することができました。
より柔軟に表記を変えることができて良いですね。

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