0

A shiny app displays a sentence.

When a user selects some part of sentence and clicks the Mark button to add markup, the sentence should be updated to reflect the action.

Example:
Sample input: A sample sentence for demo
Selection: sentence for
Desired output: A sample <markup> sentence for </markup> demo

Following is the shiny app code and the relevant JavaScript code:

library(shiny)
ui <- fluidPage(
  tags$head(tags$script(src="addMarkup.js")),
  titlePanel("Mark text selection"),
    mainPanel(htmlOutput("content"),
      actionButton("Mark", "Mark", onclick="addMarkup()")
    )
  )

server <- function(input, output) {
  sentence <- "A sample sentence for demo" 
  output$content <- renderText(sentence)
}

shinyApp(ui = ui, server = server)

addMarkup.js

function addMarkup(){
  var sent="";
  sent= document.getElementById("content").innerHTML;
  var selection="";
  if(window.getSelection){
    selection = window.getSelection().toString();
  }
  else if(document.selection && document.selection.type != "Control"){
    selection = document.selection.createRange().text;
  }
  marked = "<markup>".concat(selection).concat("</markup>");
  result = sent.replace(selection, marked);
  alert(result);
  document.getElementById("content").innerHTML = result;
}

Problem: The alert(result) does show the desired output, but the subsequent line does not update the content.

How can I achieve this functionality?

Please also suggest if a pure shiny solution exists (How can I achieve without involving JavaScript).

4

1 回答 1

0

Your code is working. the problem is that the <markup> tag does not exists in HTML. If you change <markup> to <mark>, it will work.

marked = "<mark>".concat(selection).concat("</mark>");

enter image description here

于 2017-01-06T16:18:26.863 回答