Jeremy G
Jeremy G

Reputation: 2409

d3 adding html links to a column of data in a table

I'm new to d3 and Javascript and I am trying to add an <a> element (with an href attribute) to each value in a specified column of data. Currently I'm using the following code to produce the table:

function tabulate(data, columns) {
var table = d3.select("#data_table").append("table"),
    thead = table.append("thead"),
    tbody = table.append("tbody");

// append the header row
thead.append("tr")
    .selectAll("th")
    .data(columns)
    .enter()
    .append("th")
    .text(function(column) {
        return column;
    })
    .on('click', function (d) {
        rows.sort(function (a, b) {
            if (isNaN(a[d])) {
                return d3.ascending(a[d], b[d]);
            }
            else {
                return b[d] - a[d];
            }
        });
    });
// create a row for each object in the data
var rows = tbody.selectAll("tr")
    .data(data)
    .enter()
    .append("tr");

// create a cell in each row for each column
var cells = rows.selectAll("td")
    .data(function(row) {
        return columns.map(function(column) {
            return {
                column: column, value: row[column]
            };
        });
    })
    .enter()
    .append("td")
    .html(function(d) {
        return (d.value);
    });

return table;
}
//render the data
tabulate(data, ["NAME", "1", "2", "3", "4"]);

I want to make every value in the "NAME" column a hyperlink to a website based on the value in the cell. E.G.: If there is a value in the name column that is "my_value", it will be a hyperlink to "http://test/my_value". Any help is appreciated!

Upvotes: 2

Views: 1997

Answers (1)

Tim B
Tim B

Reputation: 1983

You have to append a link after filtering the data like that :

cells.filter(function(d, i) { return i === 0})
    .append("a")
    .attr("href", function(d) {
        return "http://test/" + d.value;
    })
    .html(function(d) {
        return (d.value);
    });

See https://jsfiddle.net/o64e570x/1/

It's also possible to filter with the column name with

 cells.filter(function(d, i) { return d.column === "NAME"})

Upvotes: 4

Related Questions