LoginSignup
1
0

More than 5 years have passed since last update.

d3.jsで、<select>と<option>に別データをバインドしてみた

Posted at

やりたいこと

d3.jsを使って、Objectのarrayに格納したデータと連動した、<select>が並んだリストを作りたい。
<option>もさくっと配列にしといて連動してくれたらいいな(ゴリゴリかくのも面白くない

実装

// バインドする対象
var foo = [
    {
        "id": "A", // バインドするリストのユニークなID
        "name": "rowA", // ラベル
        "num": 1 // これをselectでデフォルト選択状態にしたい
    },
    {
        "id": "B",
        "name": "rowB",
        "num": 3
    }
];

// option選択肢
var opt = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

// <ul>の下に、foo配列1要素=1<li>としてバインド
var l = d3.selectAll("ul#foo_list")
    .selectAll("li")
    .data(foo, function (d) {
        return d.id;
    }).enter().append("li");

// <label>追加
l.append("label")
    .attr("for", function (d) {
        return d.id;
    })
    .html(function (d) {
        return d.name;
    });

// セレクトボックス本体をバインド
var s = l.append("select")
    .attr("id", function (d) {
        return d.id;
    });

// <option>の追加。バインドデータはoption選択肢リストにする。
s.selectAll("option")
    .data(opt, function (dd) {
        return dd;
    }).enter().append("option")
    .text(function (dd) {
        return dd;
    })
    .attr("value", function (dd) {
        return dd;
    });

// 上記、option追加後に、デフォルトでどれを選択状態にするかセット。
s.property("value", function (d) {
    return d.num;
});

ポイント

  • <select>をappendした状態、を変数で持っておく。
  • .property("value", 〜' は、`のappend後でないと動作しなかった。

環境

  • d3.js 4.12.0
  • HTML5
  • (一応python 3.6.0、Flask 0.12 で制作)
  • 同ページにjQuery 3.2.1 を読み込んでいるがこの部分の衝突はなし

以下の動作は確認しています
* macOS Sierra 10.12.6 Safari 11.0.3
* 同mac Chrome最新
* iOS 11.2.2 Safari
* Android 2.0.0 Chrome 64

1
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
1
0