Skip to main content
cancel
Showing results for 
Search instead for 
Did you mean: 

July 28 - August 9 | Final Round of the Power BI Dataviz World Championships. This is your chance. Learn more

Reply
Nazim
New Member

Filter Power BI table using power BI embedded Java script

Hi all,

I am new to power Bi embedded, basically i have followed the developer tutotorial and was able to successfully run the application in visual studio code Below is the screen shot.

 

I would like to know where i can insert below filter code. My apolgies, i don't have much developer backgroud.

 

Many thanks for your support.

 

Filter i want to copy:

const filter = {
    $schema: "http://powerbi.com/product/schema#basic",
    target: {
        table: "Geo",
        column: "Region"
    },
    operator: "In",
    values: ["East"]
};

// Add the filter to the report's filters.
try {
    await report.updateFilters(models.FiltersOperations.Add, [filter]);
    console.log("Report filter was added.");
}
catch (errors) {
    console.log(errors);
}

 

 

 

 

my existing JS code:

var reports = window.reports;
var datasets = window.datasets;
var embedToken = window.embedToken;
var models = window['powerbi-client'].models;

// Generate nav links for reports and datasets
$(function () {
    var reportsList = $("#reports-list");
    var datasetsList = $("#datasets-list");

    if (reports.length == 0) {
        reportsList.append($("<li>").text("[None]"));
    }
    else {
        reports.forEach((report) => {
            var li = $("<li>");
            li.append($("<a>", {
                "href": "javascript&colon;void(0);"
            }).text(report.Name).click(() => { embedReport(report) }));
            reportsList.append(li);
        });
    }

    if (datasets.length == 0) {
        datasetsList.append($("<li>").text("[None]"));
    }
    else {
        datasets.forEach((dataset) => {
            var li = $("<li>");
            li.append($("<a>", {
                "href": "javascript&colon;void(0);"
            }).text(dataset.Name).click(() => { embedQnaDataset(dataset) }));
            datasetsList.append(li);
        });
    }
});

// Embed a report
var embedReport = (report, editMode) => {

    // Create the report embed config object
    var config = {
        type: 'report',
        id: report.Id,
        embedUrl: report.EmbedUrl,
        accessToken: embedToken,
        tokenType: models.TokenType.Embed,
        permissions: models.Permissions.All,
        viewMode: editMode ? models.ViewMode.Edit : models.ViewMode.View,
        settings: {
            panes: {
                filters: { visible: false },
                pageNavigation: { visible: false }
            },
            extensions: [
                {
                    command: {
                        name: "showValue",
                        title: "Show value in alert box",
                        selector: {
                            $schema: "http://powerbi.com/product/schema#visualSelector",
                            visualName: "bf36eb378296825d9db9" // Monthly sales trends
                        },
                        extend: {
                            visualContextMenu: {
                                title: "Show value in alert box"
                            }
                        }
                    }
                }
            ]
        }
    };

    // Get a reference to the embed container
    var embedContainer = document.getElementById('embed-container');

    // Embed the report
    var embeddedReport = powerbi.embed(embedContainer, config);

    // Add "Show value" context menu item
    embeddedReport.on("commandTriggered", function (command) {
        // Determine the command detail
        var commandDetails = command.detail;
        
        // If the command is showValue, show an alert box
        if (commandDetails.command === "showValue") {
            // Retrieve specific details from the selected data point
            const category = commandDetails.dataPoints[0].identity[0].equals;
            const value = commandDetails.dataPoints[0].values[0].formattedValue;
            
            alert(category + " value is " + value);
        }
    });
}

// Embed the Q&A experience
var embedQnaDataset = (dataset) => {

    // Create the Q&A embed config object
    var config = {
        type: 'qna',
        tokenType: models.TokenType.Embed,
        accessToken: embedToken,
        embedUrl: dataset.EmbedUrl,
        datasetIds: [dataset.Id],
        viewMode: models.QnaMode.Interactive
    };

    // Get a reference to the embed container
    var embedContainer = document.getElementById('embed-container');

    // Embed the Q&A experience
    var embeddedObject = powerbi.embed(embedContainer, config);
}

// Filter reports by product demographic
$(document).ready(function () {
	$('#demographic').change(function () {
		const report = powerbi.embeds[0];
		const demographic = this.value;

		const removeFilters = (demographic == "*");
		const basicFilter = {
			"$schema": "http://powerbi.com/product/schema#basic",
			"target": {
				"table": "Product",
				"column": "Demographic"
			},
			"operator": removeFilters ? "All" : "In",
			"values": removeFilters ? [] : [demographic]
		}
		
		// Update filters
		report.updateFilters(models.FiltersOperations.Replace, [basicFilter])
			.catch(error => { console.log(error); });
	});
});


 

 

Project folder:

Nazim_0-1650730207870.png

 

1 ACCEPTED SOLUTION
Anonymous
Not applicable

Hi @Nazim ,

 

You may refer to this offical blog: Control report filters

Code:

var accessToken = "@Model.EmbedToken.Token";

    // Read embed URL from Model
    var embedUrl = "@Html.Raw(Model.EmbedUrl)";

    // Read report Id from Model
    var embedReportId = "@Model.Id";

    // Get models. models contains enums that can be used.
    var models = window['powerbi-client'].models;

    // Get a reference to the embedded report HTML element
    var reportContainer = $('#embedContainer')[0];

    if ("@Model.Username" != "") {
        $("#RLS").prop('checked', true);
        $("#RLSdiv").show();
    }
    else
    {
        $("#RLS").prop('checked', false);
        $("#RLSdiv").hide();
    }

    if ("@Model.IsEffectiveIdentityRequired.GetValueOrDefault()" == "True") {
        $("#noRLSdiv").hide();
        $("#RLS").removeAttr("disabled");
        $("#RLS").change(function () {
            if ($(this).is(":checked")) {
                $("#RLSdiv").show(300);
            } else {
                $("#RLSdiv").hide(200);
            }
        });
    }
    else
    {
        $("#noRLSdiv").show();
    }

    const testFilter = {
        $schema: "http://powerbi.com/product/schema#basic",
        target: {
            table: "SampleParameter",
            column: "AgentID"
        },
        operator: "In",
        values: ["H1627"]
    };

    // Embed configuration used to describe the what and how to embed.
    // This object is used when calling powerbi.embed.
    // This also includes settings and options such as filters.
    // You can find more information at https://github.com/Microsoft/PowerBI-JavaScript/wiki/Embed-Configuration-Details.
    var config = {
        type: 'report',
        tokenType: models.TokenType.Embed,
        accessToken: accessToken,
        embedUrl: embedUrl,
        id: embedReportId,
        permissions: models.Permissions.All,//models.Permissions.Read
        //can add filters here
        filters: [testFilter], //filter array here
        settings: {
            filterPaneEnabled: true,
            navContentPaneEnabled: true //the nav at bottom of report
        },
        //filterType: models.FilterType.BasicFilter
    };

    // Embed the report and display it within the div container.
    var report = powerbi.embed(reportContainer, config);

For refernece: Embed Report Filter not working

 

Best Regards,
Rico Zhou

 

If this post helps, then please consider Accept it as the solution to help the other members find it more quickly.

View solution in original post

1 REPLY 1
Anonymous
Not applicable

Hi @Nazim ,

 

You may refer to this offical blog: Control report filters

Code:

var accessToken = "@Model.EmbedToken.Token";

    // Read embed URL from Model
    var embedUrl = "@Html.Raw(Model.EmbedUrl)";

    // Read report Id from Model
    var embedReportId = "@Model.Id";

    // Get models. models contains enums that can be used.
    var models = window['powerbi-client'].models;

    // Get a reference to the embedded report HTML element
    var reportContainer = $('#embedContainer')[0];

    if ("@Model.Username" != "") {
        $("#RLS").prop('checked', true);
        $("#RLSdiv").show();
    }
    else
    {
        $("#RLS").prop('checked', false);
        $("#RLSdiv").hide();
    }

    if ("@Model.IsEffectiveIdentityRequired.GetValueOrDefault()" == "True") {
        $("#noRLSdiv").hide();
        $("#RLS").removeAttr("disabled");
        $("#RLS").change(function () {
            if ($(this).is(":checked")) {
                $("#RLSdiv").show(300);
            } else {
                $("#RLSdiv").hide(200);
            }
        });
    }
    else
    {
        $("#noRLSdiv").show();
    }

    const testFilter = {
        $schema: "http://powerbi.com/product/schema#basic",
        target: {
            table: "SampleParameter",
            column: "AgentID"
        },
        operator: "In",
        values: ["H1627"]
    };

    // Embed configuration used to describe the what and how to embed.
    // This object is used when calling powerbi.embed.
    // This also includes settings and options such as filters.
    // You can find more information at https://github.com/Microsoft/PowerBI-JavaScript/wiki/Embed-Configuration-Details.
    var config = {
        type: 'report',
        tokenType: models.TokenType.Embed,
        accessToken: accessToken,
        embedUrl: embedUrl,
        id: embedReportId,
        permissions: models.Permissions.All,//models.Permissions.Read
        //can add filters here
        filters: [testFilter], //filter array here
        settings: {
            filterPaneEnabled: true,
            navContentPaneEnabled: true //the nav at bottom of report
        },
        //filterType: models.FilterType.BasicFilter
    };

    // Embed the report and display it within the div container.
    var report = powerbi.embed(reportContainer, config);

For refernece: Embed Report Filter not working

 

Best Regards,
Rico Zhou

 

If this post helps, then please consider Accept it as the solution to help the other members find it more quickly.

Helpful resources

Announcements
FabCon and SQLCon Barcelona 2026

FabCon & SQLCon – Barcelona 2026

Join us in Barcelona for FabCon and SQLCon, the Fabric, Power BI, SQL, and AI community event. Save €200 with code FABCMTY200.

Fabric Community Sticker Design Challenge Barcelona Carousel

Fabric Community Sticker Challenge - Barcelona 2026

If you love stickers, then you will definitely want to check out our community sticker challenge, Barcelona edition!

July Power BI Update Carousel

Power BI Monthly Update - July 2026

Check out the July 2026 Power BI update to learn about new features.

Power BI DataViz World Championships carousel

Power BI DataViz World Championships - June 2026

A new Power BI DataViz World Championship is coming this June! Don't miss out on submitting your entry.