【发布时间】:2017-04-17 06:24:19
【问题描述】:
我的 Shiny 应用程序允许用户动态创建/删除输入。
然后我遍历这些输入以获取值(例如 val1
我的问题是来自已删除输入的值仍保留在闪亮的“输入”列表中。
我尝试使用 removeUI 或 javascript(加上 unbindAll/bindAll)删除 html 小部件,但它没有帮助,我猜是因为一旦值在“输入”列表中,它就会一直保留在那里,直到 UI 上的某些内容更新它.
我还尝试编辑“输入”列表本身(在服务器端),但我收到错误,因为它是只读的。
关于如何从已删除的闪亮输入小部件中清除“输入”列表的任何想法?
下面是一个小项目的代码来说明问题:
ui.R
library(shiny)
# Define UI for dataset viewer application
shinyUI(fluidPage(
# Javascript to handle the add/remove action of inputs
tags$head(tags$script(src="script.js")),
# Container where the script adds the dynamic inputs
tags$div(id = "container_for_dynamic_inputs"),
# 'Add' button
tags$button(onclick="addNewInputText()",
class = "btn btn-default",
"Add input"),
# 'Remove' button
tags$button(onclick="removeLastInputText()",
class = "btn btn-default",
"Remove input"),
# Keeps tracks of the number of inputs (see server.R)
verbatimTextOutput("summary")
)
)
www/script.js
var number_of_dynamic_inputs = 0;
var addNewInputText = function () {
console.log("addNewInputText");
var container_elt = document.getElementById("container_for_dynamic_inputs");
Shiny.unbindAll(container_elt);
var new_input = document.createElement("input");
var id = "input_" + number_of_dynamic_inputs++;
new_input.setAttribute("id", id);
new_input.setAttribute("name", id);
new_input.setAttribute("type", "text");
new_input.setAttribute("value", id);
container_elt.append(new_input);
Shiny.bindAll(container_elt);
}
var removeLastInputText = function () {
var container_elt = document.getElementById("container_for_dynamic_inputs");
Shiny.unbindAll(container_elt);
number_of_dynamic_inputs--;
var id = "input_" + number_of_dynamic_inputs ;
console.log("removeLastInputText: ", id);
var elementToRemove = document.getElementById(id);
container_elt.removeChild(elementToRemove);
Shiny.bindAll(container_elt);
}
server.R
library(shiny)
shinyServer(function(input, output) {
output$summary <- renderPrint({
for (i in names(input)) {
print(input[[i]])
}
})
})
【问题讨论】:
-
我也试过使用shinyjs函数'reset',没有更好的结果
-
你能提供一个更好的例子,代码可以运行吗
-
@PorkChop:我添加了一个项目的代码来说明问题
标签: shiny