使用JavaScript筛选嵌入式Tableau可视化图表时的空格值过滤问题求助
Hey there! I see exactly what's causing your filter to fail when dealing with state names that have spaces (like "West Virginia"). Let's break down the problem and fix it step by step.
The Root Cause
In your viz-filter element, you're setting the value attribute without wrapping ${State} in quotes:
<viz-filter field="State" value=${State}></viz-filter>
When the user enters a name with spaces (e.g., "West Virginia"), the rendered HTML becomes:
<viz-filter field="State" value=West Virginia></viz-filter>
HTML interprets this as two separate attributes: value=West and Virginia (an invalid attribute), so Tableau only gets "West" as the filter value—hence the broken functionality.
Additionally, you have a duplicate </viz-filter> closing tag in your code, which can cause DOM structure issues that might also interfere with the visualization.
The Fix
Wrap the value attribute's dynamic content in double quotes, and remove the extra closing tag. Here's the corrected show() function:
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> </tableau-viz> `; }
Key Changes:
- Added double quotes around
${State}invalue="${State}"to ensure the entire state name (including spaces) is treated as a single attribute value. - Removed the extra
</viz-filter>tag to fix the DOM structure.
Full Corrected Code
Here's the complete working HTML file:
<!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> </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>
This fix will work for single states with spaces (like "West Virginia") and multiple states separated by commas (like "West Virginia,Oregon")—the quotes ensure the entire comma-separated string is passed as a single filter value to Tableau.
内容的提问来源于stack exchange,提问作者Ariguru

