Simon Breton
Simon Breton

Reputation: 2876

Filter data by using checkbox for a table with D3.js

I'm trying to build a table where I can filter my data using a checkbox. Basically I have a column with Authorname and another column with Linkclicks. I would like to be able to update my table by selecting only one author. For the test I've build only one check box :

<label><input type="checkbox" name="authorfilter" class="author_nd" value="Juliette Geenens" checked="checked"/> Juliette Geenens</label>

I also know I need this line of code to apply my filter based on the checkbox event :

d3.selectAll(".author_nd").on("change", function() {
    var type = this.value;
    if (this.checked) { 
        var filtereddata = people.filter(function(d){ return d.authorname == type;});
    } 
});

However, I don't know where I should put these line of code.... I'm new to D3 and I still don't really understand how data are moving from a function to a variable and so on...

Here is my whole code :

<!DOCTYPE html>
<html lang="en">
<head>

<script src="https://d3js.org/d3.v3.min.js"></script>

<style>
    td, th {
    padding: 2px 4px;
}

th {
    font-weight: bold;
}   
</style>

</head>

<body>

    <div id="container">

 <script>   


var table = d3.select("#container").append("table");
var thead = table.append("thead");
var tbody = table.append("tbody");

// append the header row
thead.append("tr")
  .selectAll("th")
  .data(["authorname", "linkclicks"])
  .enter()
  .append("th")
  .text(function(column) { return column; })

function update(data) {
  var transformedData = d3.nest()
    .key(function(d) { return d.authorname;})
    .rollup(function(d) { return d3.sum(d, function(g) {return g.linkclicks;}); })
    .entries(data);

  var tr = tbody
    .selectAll("tr")
    .data(transformedData)
    .enter()
    .append('tr')
    .sort(function(a, b) {
      return d3.descending(a.values, b.values)
    });

  tr
    .append('td')
    .text(function(d) { return d.key; });
  tr
    .append('td')
    .text(function(d) { return d.values;})
};


var url = 'data.json';

d3.json(url, function(error, people) {
if (error) {
throw error;}
update(people);});


</script>
</div>
</body>

</html>

Upvotes: 1

Views: 918

Answers (1)

Gerardo Furtado
Gerardo Furtado

Reputation: 102194

As people only exists inside the JSON function, try to put your code inside it as well:

d3.json(url, function(error, people) {
  if (error) {
    throw error;}
  update(people);

d3.selectAll(".author_nd").on("change", function() {
  var type = this.value;
  if (this.checked) { 
    var filtereddata = people.filter(function(d){ return d.authorname == type;});
    update(filtereddata);
  }
});

});

The problem is, without seeing your data I don't know what d3.nest is going to do, and it will probably return an error.

Upvotes: 1

Related Questions