Created
May 8, 2018 08:41
-
-
Save cecilialee/93dc25ee1a83b646d1ed3afcefd993bc to your computer and use it in GitHub Desktop.
Highlighted text input in Shiny #r #shiny
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
library(shiny) | |
ui <- fluidPage( | |
h2("Highlight Input Example"), | |
# sample text for selection | |
p("The insured received an examination of the large intestine in 2014. | |
As a result, everything was normal and there was no need to go back | |
to the follow-up consultation and any examination and treatment."), | |
# shiny text input | |
textInput("mytext1", "mytext1"), | |
textInput("mytext2", "mytext2"), | |
textInput("mytext3", "mytext3"), | |
# submit | |
actionButton("submit", "Submit"), | |
hr(), | |
# display submited inputs | |
verbatimTextOutput("results"), | |
# javascript code to send data to shiny server | |
tags$script(' | |
function getSelectionText() { | |
var text = ""; | |
if (window.getSelection) { | |
text = window.getSelection().toString(); | |
} else if (document.selection) { | |
text = document.selection.createRange().text; | |
} | |
return text; | |
} | |
document.onmouseup = document.onkeyup = document.onselectionchange = function() { | |
var selection = getSelectionText(); | |
Shiny.onInputChange("selected_text", selection); | |
} | |
document.onclick = function() { | |
var focusedElement = document.activeElement.id; | |
Shiny.onInputChange("focus_input", focusedElement); | |
} | |
') | |
) | |
server <- function(input, output, session) { | |
# update text input | |
observe({ | |
updateTextInput(session, input$focus_input, value = input$selected_text) | |
}) | |
# initiate reactive values | |
values <- reactiveValues( | |
results = NULL | |
) | |
# store submited inputs | |
observeEvent(input$submit, { | |
values$results <- c(input$mytext1, input$mytext2, input$mytext3) | |
}) | |
# render submitted inputs | |
output$results <- renderPrint({ | |
values$results | |
}) | |
} | |
shinyApp(ui, server) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment