Skip to content

Instantly share code, notes, and snippets.

@cecilialee
Created May 8, 2018 08:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cecilialee/93dc25ee1a83b646d1ed3afcefd993bc to your computer and use it in GitHub Desktop.
Save cecilialee/93dc25ee1a83b646d1ed3afcefd993bc to your computer and use it in GitHub Desktop.
Highlighted text input in Shiny #r #shiny
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