How to Use the `onField` Event to Dynamically Change Chart Field Data in OrgChart JS
When building an interactive org chart with OrgChart JS, sometimes you want to dynamically transform the data before it's displayed. One powerful way to do this is by using the onField
event.
In this post, we’ll walk through a simple example: displaying salary data with a dollar sign using the onField
event.
Code Example
Step 1: Include OrgChart JS and Create the Chart
Start by including the OrgChart library in your HTML and creating a container element for your chart.
<script src="https://cdn.balkan.app/orgchart.js"></script>
<div id="tree"></div>
Then, create a new chart instance with your desired configuration. Here, we’ll use dark mode and enable mouse scroll:
var chart = new OrgChart(document.getElementById("tree"), {
mode: 'dark',
mouseScrool: OrgChart.action.scroll,
nodeBinding: {
field_0: "name",
field_1: "salary"
}
});
field_0
and field_1
are placeholders in the chart template where we bind our data fields (name
and salary
respectively).
Step 2: Prepare and Load Data
Next, define your data in an array of node objects. Each node can have any custom properties—like name
and salary
.
let nodes = [
{ id: 1, name: "John Doe", salary: "60000" },
{ id: 2, pid: 1, name: "Jane Smith", salary: "50000" }
];
We’ll load this data into the chart after we set up our onField
event, so it’s formatted correctly on render.
Step 3: Use onField
to Format the Salary Field
Before loading the data, use the onField
event to intercept and customize how a field is displayed. This is the key part:
chart.onField((args) => {
if (args.name == "salary") {
args.value = `$${args.data.salary}`;
}
});
What’s Happening Here?
args.name
refers to the field in the template (in this case, "salary"
mapped to field_1
).
args.data.salary
is the raw value from the data object.
We set args.value
to a string with a dollar sign, which updates what’s shown in the chart.
Step 4: Load the Data
Now that the onField
event is set up, go ahead and load the data into the chart:
chart.load(nodes);
This triggers the rendering process, and because the onField
event is already active, the salary values will appear formatted with dollar signs.
Here’s the Full Code Example
Conclusion
Using the onField
event in OrgChart JS is a flexible way to transform how data appears in your chart—whether that’s formatting numbers, adding units, or combining multiple fields. Try experimenting with other fields and custom logic to make your charts more informative and visually polished.
Happy charting!