如何使用更新的UI在Shiny中格式化numericInput?

时间:2019-04-09 03:04:10

标签: javascript r shiny format shiny-reactivity

以下工作示例来自于我先前的问题Prevent an event happened in Shiny if no UI inputs are available。现在,我想用逗号来格式化numericInput字段,以帮助用户读取大量数字。我按照本文“ https://beta.rstudioconnect.com/barbara/format-numbers/”中第2个选项的示例,以这种样式更改了Total numericInput。关键是创建一个.js文件,该文件将数字格式化并将其存储在与闪亮脚本相同的文件夹下的www目录中。

这与Total numericInput很好地配合。但是,如何为更新后添加的numericINputs使用相同的格式?面临的挑战是我不知道以后会添加多少numericInput,因此如果我不知道要添加到该文件的Inpur ID,很难修改format_numbers.js文件。 / p>

format_numbers.js如下。

$(document).ready(function() {
  // Helper function to guarantee cross-browser compatibility
  // adapted from: http://stackoverflow.com/a/16157942
  function localeString(x, sep, grp) {
    var sx = (''+x).split('.'), s = '', i, j;
    sep || (sep = ',');            // default separator
    grp || grp === 0 || (grp = 3); // default grouping
    i = sx[0].length;
    while (i > grp) {
      j = i - grp;
      s = sep + sx[0].slice(j, i) + s;
      i = j;
    }
    s = sx[0].slice(0, i) + s;
    sx[0] = s;
    return sx.join('.');
  }

  // To change Total's input field (lose arrows and other functionality)
  $('#Total')[0].type = 'text';

  // To format the number when the app starts up
  $('#Total').val(localeString($('#Total').val()));

  // To format the number whenever the input changes
  $('#Total').keyup(function(event) {
    $(this).val(localeString($(this).val().replace(/,/g, '')));
  });
});

闪亮的脚本如下。

library(shiny)

# Define UI
ui <- fluidPage(
  # Modify tags
  tags$head(tags$script(src = "format_numbers.js")),

  # Action button to add numeric input
  actionButton("add", "Add UI"),
  actionButton("sum", "Sum"),

  # Numeric Input
  numericInput(inputId = "Total", label = "Total", value = 0),

  # Text output
  "The number is ", 
  textOutput(outputId = "out_num", inline = TRUE)

)

# Server logic
server <- function(input, output, session){

  # Add numeric input
  observeEvent(input$add, {
    insertUI(
      selector = "#add",
      where = "afterEnd",
      ui = numericInput(paste0("txt", input$add), label = "Number", value = 0)
    )
  })

  # Reactive values for Total
  Num_In <- reactiveValues(
    Total_In = 0
  )

  # Convert number to character
  # This is to fill in the Total numeric input formatting with comma
  total_num_as_char <- reactive({format(Num_In$Total_In, big.mark = ",", trim = TRUE)})

  total_input <- reactive({Num_In$Total_In})

  observeEvent(input$sum, {
    num_names <- names(input)[grepl("^txt", names(input))]

    if (length(num_names) == 0) {
      foo <- 0
    } else {
      foo <- sum(sapply(num_names, function(x) input[[x]]), na.rm = TRUE)
    } 
    Num_In$Total_In <- foo

    updateNumericInput(session = session,
                       inputId = "Total", 
                       value = total_num_as_char())
  })

  # Convert input to numeric
  total_num <- reactive({as.numeric(gsub(",", "", input$Total))})

  # Create text output
  output$out_num <- renderText({total_num()})
}

# Complete app with UI and server components
shinyApp(ui, server)

1 个答案:

答案 0 :(得分:1)

对我来说,以下工作。

将UI组件添加到insertUI时,将触发JS事件shiny:bound。然后我们可以利用它:

  // Helper function to guarantee cross-browser compatibility
  // adapted from: http://stackoverflow.com/a/16157942
  function localeString(x, sep, grp) {
    var sx = (''+x).split('.'), s = '', i, j;
    sep || (sep = ',');            // default separator
    grp || grp === 0 || (grp = 3); // default grouping
    i = sx[0].length;
    while (i > grp) {
      j = i - grp;
      s = sep + sx[0].slice(j, i) + s;
      i = j;
    }
    s = sx[0].slice(0, i) + s;
    sx[0] = s;
    return sx.join('.');
  }

$(document).ready(function() {
  // To change Total's input field (lose arrows and other functionality)
  $('#Total')[0].type = 'text';

  // To format the number when the app starts up
  $('#Total').val(localeString($('#Total').val()));

  // To format the number whenever the input changes
  $('#Total').keyup(function(event) {
    $(this).val(localeString($(this).val().replace(/,/g, '')));
  });
});

$(document).on('shiny:bound', function(evt){
  var id = evt.target.getAttribute('id');
  if((/^(txt)/).test(id)){
    var selector = '#' + id; 
    $(selector)[0].type = 'text';
    $(selector).val(localeString($(selector).val()));
    $(selector).keyup(function(event) {
      $(this).val(localeString($(this).val().replace(/,/g, '')));
    });
  }
});

现在,在R中:

unformat <- function(x) as.numeric(gsub(",", "", x))

  observeEvent(input$sum, {
    num_names <- names(input)[grepl("^txt", names(input))]

    if (length(num_names) == 0) {
      foo <- 0
    } else {
      foo <- sum(sapply(num_names, 
                        function(x) unformat(input[[x]])), na.rm = TRUE)
    } 
    Num_In$Total_In <- foo

    updateNumericInput(session = session,
                       inputId = "Total", 
                       value = total_num_as_char())
  })