cpa
cpa

Reputation: 3884

Bootstrap popover in a table generated with jQuery

I am trying to build a table with JSON data I get with ajax.

 $.getJSON('http://localhost:8000/list' , function(data) {
        var tbl_body = '<div class="table-responsive"><table class="table table-hover"><tr><th>Description</th><th>Chez…</th><th></th><th></th></tr>';
        $.each(data, function() {
            var d = this[1];
            var tbl_row = "<td>" + d['title'] + "</td>";
            tbl_row += '<td><a href="#" data-html="true" data-toggle="popover" data-content="' + d['owner']['phone'] + '">' + d['owner']['name'] + '</a></td>';
            tbl_body += "<tr>"+tbl_row+"</tr>";
        });
        tbl_body += "</table></div>";
        console.log(tbl_body);
        $("#liste").html(tbl_body).text();
    });

The JSON data looks like this:

[
  [
    0,
    {
      "title": "Why",
      "author": "How",
      "detailsUrl": null,
      "owner": {
        "name": "Ted",
        "email": "[email protected]",
        "phone": "098765645565"
      },
      "coverUrl": null,
      "history": [ 
      ]
    }
  ],
  [
    1,
    {
      "title": "Test",
      "author": "Test",
      "detailsUrl": null,
      "owner": {
        "name": "Fred",
        "email": "[email protected]",
        "phone": "98976567"
      },
      "coverUrl": null,
      "history": [
      ]
    }
  ]
]

But when I click the generated link in the table, nothing happens. I am sure that I am using bootstrap correctly because it works in a write plain HTML by hand. I guess that's an issue with escaping.

Upvotes: 1

Views: 1471

Answers (1)

Arun P Johny
Arun P Johny

Reputation: 388316

You need to initialize the plugin once the elements are added to the dom

$.getJSON('http://localhost:8000/list', function (data) {
    var tbl_body = '<div class="table-responsive"><table class="table table-hover"><tr><th>Description</th><th>Chez…</th><th></th><th></th></tr>';
    $.each(data, function () {
        var d = this[1];
        var tbl_row = "<td>" + d['title'] + "</td>";
        tbl_row += '<td><a href="#" data-html="true" data-toggle="popover" data-content="' + d['owner']['phone'] + '">' + d['owner']['name'] + '</a></td>';
        tbl_body += "<tr>" + tbl_row + "</tr>";
    });
    tbl_body += "</table></div>";
    console.log(tbl_body);
    $("#liste").html(tbl_body).text();

    $("#liste").find('a[data-toggle="popover"]').popover();
});

Demo: Fiddle

Upvotes: 1

Related Questions