javascript R shiny:如何使用shinyjs清除带有默认值的输入字段?

a11xaf1n  于 2022-12-17  发布在  Java
关注(0)|答案(2)|浏览(141)

我正在尝试使用shinyjs包来清除和禁用shiny应用中的一个默认输入字段。清除/禁用按钮似乎可以工作。但是,当我点击提交时,默认值仍在提交(见下图)。我如何使其提交NULL或空字符串?

library(shinyjs)
library(shiny)

# this is supposed to change the input value to null
jsCode <- 'shinyjs.clear_input = function(params){
    var defaultParams = {
    input_id : null
  };
  params = shinyjs.getParams(params, defaultParams);
  var el = $("#" + params.input_id);
    el.val(null);}'

  shinyApp(

    ui = fluidPage(
      useShinyjs(),  
      extendShinyjs(text = jsCode, functions = c("clear_input")),
      textInput("input",  label = "input", value = "default text"),
      actionButton("clear", label = "clear/disable"),
      actionButton("submit", "submit"),
      tags$div(id="result")
      ),
    server = function(input, output) {
      
      observeEvent(input$clear, {
        js$clear_input("input")
        disable("input")
      })

      observeEvent(input$submit, {
        insertUI("#result", ui=renderText(input$input))
      })
    }
  )
qjp7pelc

qjp7pelc1#

就我个人而言,我对javascript不是很适应,所以我尽可能地避免使用javascript,并在R中使用它。您可以使用updateTextInput更新textInput中的值。

library(shiny)
library(shinyjs)

shinyApp(
  ui = fluidPage(
    useShinyjs(),
    textInput("input",  label = "input", value = "default text"),
    actionButton("clear", label = "clear/disable"),
    actionButton("submit", "submit"),
    tags$div(id="result")
  ),
  server = function(input, output, session) {
    
    observeEvent(input$clear, {
      updateTextInput(session, "input", value = "")
      disable("input")
    })
    
    observeEvent(input$submit, {
      insertUI("#result", ui=renderText(input$input))
    })
  }
)

kxeu7u2r

kxeu7u2r2#

使用updateTextInput()时坚持使用Javascript并遵循Ronak的想法

library(shinyjs)
library(shiny)

# this is supposed to change the input value to null
jsCode <- 'shinyjs.clear_input = function(params){
    var defaultParams = {
    input_id : null
  }
  ;
  params = shinyjs.getParams(params, defaultParams);
  var el = $("#" + params.input_id);
    el.val(null);}'

shinyApp(
  
  ui = fluidPage(
    useShinyjs(),  
    extendShinyjs(text = jsCode, functions = c("clear_input")),
    textInput("input",  label = "input", value = "default text"),
    actionButton("clear", label = "clear/disable"),
    actionButton("submit", "submit"),
    tags$div(id="result")
  ),
  server = function(input, output) {
    
    observeEvent(input$clear, {
      updateTextInput(inputId="input", value=js$clear_input("input"))
      disable("input")
    })
    
    observeEvent(input$submit, {
      insertUI("#result", ui=renderText(input$input))
    })
  }
)

相关问题