[英]R shiny: how to clear an input field with a default value using shinyjs?
[英]Reset customized input shiny R using shinyjs::reset
我有一个用于自定义输入的 shiny 模块,并且我正在尝试添加一个按钮以在每次单击此按钮时重置此自定义输入(接口和服务器)。 下面是一个使用 shinyjs::reset 的示例:
app.R
library(shinyjs)
library(rintrojs)
library(shinydashboard)
library(shinyWidgets)
source("customTextInput.R", local = TRUE, encoding = "UTF-8")
ui <- fluidPage(
useShinyjs(),
# Assembling page
dashboardPage(
# Assembling header
dashboardHeader(title = "Custom Inputs", titleWidth = 1294),
# Assembling sidebar
dashboardSidebar(
sidebarMenu(
menuItem("Custom inputs reset", tabName = "custom", icon = icon("search"))
)
),
# Assembling the body of the page
dashboardBody(
tabItems(
tabItem(tabName = "custom",
br(),
br(),
customTextInputUI("text1"),
fluidPage(
textInput(inputId = "text2", label = "Native text input", width = "100%"),
actionButton(inputId = "reseter1", label = "Reset custom"),
actionButton(inputId = "reseter2", label = "Reset native")
),
)
)
)
)
)
server <- function(input, output, session) {
{### Reset -----
observe({
shinyjs::onclick("reseter1", {
reset("text1")
})
})
observe({
shinyjs::onclick("reseter2", {
reset("text2")
})
})
}
}
shinyApp(ui, server)
customTextInput.R
library(shinyjs)
{# UI Module -----
customTextInputUI <- function(id, addWidth = "100%", addHeight="64px", addTop="5px", addValue = "") {
if (is.null(addValue)){addValue <- ""}
ns <- NS(id)
return(
fluidPage(
HTML(
sprintf(
"
<form id='%s' autocomplete='off' class = 'form-group shiny-input-container' style = 'padding-top:%s; width:%s; height:%s;'>
<label for='%s'>Custom text input</label>
<input charset='UTF-8' type='text' class = 'form-control'
id='%s' data-slots=' ' value = \"%s\"
data-shinyjs-resettable-id='%s' data-shinyjs-resettable-type='Text' data-shinyjs-resettable-value='' required>
</form>", ns('textBloco'), addTop, addWidth, addHeight, ns('textInput'), ns('textInput'), addValue, ns('textInput')))
)
)
}
}
在这种情况下,reseter2 可以重置 shiny text2 本机 textInput,但是 reseter1 无法重置自定义输入 text1。
为什么会有这种意想不到的行为? 是否有任何解决方法,也许使用纯 javascript?
先感谢您 !
如果您检查text1
的输入 ID,那么您将看到它显示为text1-textBloco
因此,要使您的reset
工作,您可以将其更新为reset("text1-textBloco")
那么它应该可以工作。
或者,您可以将customerTextInput.R
更新为sprintf
中ns('textBloco')
到只是id
然后它应该与app.R
中的reset("text1")
一起使用。 所以sprintf()
将类似于:
sprintf(
"
<form id='%s' autocomplete='off' class = 'form-group shiny-input-container' style = 'padding-top:%s; width:%s; height:%s;'>
<label for='%s'>Custom text input</label>
<input charset='UTF-8' type='text' class = 'form-control'
id='%s' data-slots=' ' value = \"%s\"
data-shinyjs-resettable-id='%s' data-shinyjs-resettable-type='Text' data-shinyjs-resettable-value='' required>
</form>", id, addTop, addWidth, addHeight, ns('textInput'), ns('textInput'), addValue, ns('textInput')))
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.