Reputation: 95
I am creating a shiny app where users can click on one of the cells of the 'renderDT' table to choose the text, and then this chosen text will be added into the text input box -- a function similar to when you type text on your phone, then the phone gives several candidate words for you to choose from. Then you can tap on one of the words, the word will automatically go to your text box, to finish your typing.
I was able to find the example on how to get the clicked cell's value to the output from here. Something like this on 'server.R'
shinyServer(function(input, output,session) {
output$inputecho <- reactive({
input$inputtext
})
candidates <- reactive({
candidates <- data.table(
candidate=c("word1","word2","word3")
score=c(0.2,0.13,0.12)
) ### here candidates is a dummy data with same ###structure of real data.
candidates<-as.data.frame(candidates)
candidates
})
output$candidates<-renderDT({candidates()},server=FALSE, selection = list(mode='single',target="cell"))
observeEvent(input$candidates_cell_clicked,{
info=input$candidates_cell_clicked
if (is.null(info$value)||info$col!=0)return()
updateTextInput(session,'inputtext',value=paste0(inputtext,info$value))
})
}
)
And this for 'ui.R'
shinyUI(fluidPage(
mainPanel(
textInput("inputtext", label="", value=" "),
p("Click to select from the top candidate words:"),
DT::dataTableOutput("candidates")
)
))
When I run the app, it seems that the cell can be shown as selected. However, the input text inside of my input textbox is not updated.
Upvotes: 0
Views: 4721
Reputation: 1054
Try this. The if condition was wrongly coded, and hence updateTextinput was never being called. Also, inputtext
needed to be called as input$inputtext
, if you want to paste0
with cell value being clicked.Ive left comments inline the places where I made edits. Also, i used data.frame
and not data.table
, Not that it matters.
library(shiny)
library(DT)
library(shiny)
ui <- fluidPage(
mainPanel(
textInput("inputtext", label="", value=" "),
p("Click to select from the top candidate words:"),
DT::dataTableOutput("candidates")
)
)
server <- function(input, output, session) {
output$inputecho <- reactive({
input$inputtext
})
candidates <- reactive({
candidates <- data.frame( # changed from data.table
candidate=c("word1","word2","word3") , # comma was missing
score=c(0.2,0.13,0.12)
) ### here candidates is a dummy data with same ###structure of real data.
candidates<-as.data.frame(candidates)
candidates
})
output$candidates<-renderDT({candidates()},server=FALSE, selection = list(mode='single',target="cell"))
observeEvent(input$candidates_cell_clicked,{
info=input$candidates_cell_clicked
print(info$value)
if (!(is.null(info$value)||info$col==0))# this was wrongly coded in your example
{
updateTextInput(session,'inputtext',value=paste0(input$inputtext,info$value)) # assuming you want to concatenate the two
# if you want to just update the cell do value=info$value
}
})
}
shinyApp(ui, server)
Upvotes: 1