Filtering an embedded Tableau visualization using Javascript

Viewed 12

I am quite new to Javascript and HTML. As a part of learning, I am working on a public visualization. (https://public.tableau.com/views/Superstore_24/Overview).

What I'm trying to do:

  1. Specify a region.
  2. Initialize the visualization after applying a filter based on region.
  3. Display the Tableau visualization.

The challenge:

The code works when the user input is a word without spaces (Eg: "Washington"). It also works for multiple single-word filters (Eg: "Washington,Oregon"). However it fails when the input is a word with a space (Eg: "West Virginia").

The particular snippet where I am taking input and sending it to the visualization is as follows:

 function show() {
        State = document.getElementById("Region").value; //variable to store user input
        document.getElementById("Showviz").innerHTML = 
        `
        <h3>Your visualization: ${State} </h3>
        <tableau-viz
        id="tableauViz"
        src="https://public.tableau.com/views/Superstore_24/Overview"
        device="phone"
        hide-tabs
        >
        <viz-filter field="State" value=${State}></viz-filter>
        </viz-filter>
        </tableau-viz>
        `;
      }

This is a weird problem, and I would really appreciate help on it.

Attaching the full code here:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <title>Viz</title>
  </head>
  <body>
    <script
      async
      type="module"
      src="https://public.tableau.com/javascripts/api/tableau.embedding.3.latest.min.js"
    ></script>
    <!-- Custom script starts here -->
    <script>
      var State;
      function show() {
        State = document.getElementById("Region").value; //variable to store user input
        document.getElementById("Showviz").innerHTML = `
        <h3>Your visualization: ${State} </h3>
        <tableau-viz
        id="tableauViz"
        src="https://public.tableau.com/views/Superstore_24/Overview"
        device="phone"
        hide-tabs
        >
        <viz-filter field="State" value=${State}></viz-filter>
        </viz-filter>
        </tableau-viz>
        `;
      }
    </script>
    <input
      id="Region"
      type="text"
      placeholder="Please enter your State"
      style="width: 500px"
      required
    />
    <button type="button" id="change" onclick="show()">Click Me!</button>
    <!-- Viz is displayed here -->
    <p id="Showviz"></p>
  </body>
</html>

0 Answers
Related