values not updating after hiding/showing sections

91 Views Asked by At

I am trying to create a flexdashboard with shiny that renders a section containing a valueBox. However, this section should only be visible when the displayed value is not 0. Otherwise the boxes should be shown and populated with the selected value.

enter image description here

Building on this answer the first part works by using js code (see below) and the section disappears when the value is 0

enter image description here

but the value does not change back when the input changes

enter image description here

I found this possibly related answer but am unable to adapt it to my use-case.

So here is my code starting with the the YAML of the .rmd file

---
title: "Test"
output: 
  flexdashboard::flex_dashboard:
    vertical_layout: scroll
runtime: shiny
---

library(flexdashboard)
library(shiny)

numericInput("obs", "Observations:", 0, min = 0, max = 1)

Valuebox {.value-box #box}

renderValueBox({
  valueBox(input$obs)
})

and the js code that search all sections containing "box" and hides them when its value-ouput is 0

$(document).on("shiny:inputchanged", function (event) {
    // Find all sections with IDs containing "box"
    var sections = $('[id*="box"]');
    
    // Check if the input with id "obs" has changed
    if (event.name === 'obs') {
        // Show all sections
        sections.show();
        return;
    }

    // Loop through each section
    sections.each(function() {
        var section = $(this);
      
        var valueOutput = section.find('.value-output');

        // Check if the value is 0 and hide or show the section accordingly
        if (valueOutput.length > 0) {
            if (parseFloat(valueOutput.text()) === 0) {
                section.hide();
            } else {
                section.show();
            }
        }
    });
});

Any help is much appreciated :)

1

There are 1 best solutions below

0
Ben Nutzer On

According to this forum post the output must resume while hidden. This can be done by setting suspendWhenHidden to FALSE.

outputOptions(output, "id", suspendWhenHidden = FALSE)

I found it tricky to pinpoint the exact id of the output in question when using flexdashboard. It appears to be some random id that is created on start-up of the app, e.g. out2132b.... Since there is an order to the outputs one can address them by position

outputs <- names(outputOptions(output))
outputOptions(output, outputs[2], suspendWhenHidden = FALSE)

Or iterate over all of them. Now, the values should be updated even when the section in question is hidden.