Home > Software design >  passing a variable to JS in shiny
passing a variable to JS in shiny

Time:06-30

Below is the sample action button with JS in it.This is hard coded. But actually, the 'small_ID' below is very dynamic and will get changed. So how can i pass a variable inside document.getElementById ? Can anyone help?

actionButton("show1",class = "act_button", list(span(id = "m1", , "Model 1"), span(, Sys.time())),
                         onclick = "Shiny.setInputValue('btnid', document.getElementById('small_ID').textContent);")

CodePudding user response:

You could do this with paste:

actionButton(
    "show1",
    class = "act_button", 
    list(
        span(id = "m1", , "Model 1"), 
        span(, Sys.time())
    ),
    onclick = paste(
       "Shiny.setInputValue('btnid', document.getElementById('",
       small_ID,
       "').textContent);",
       sep=""
    )
)

...where small_ID should be your variable holding the id.

CodePudding user response:

You can insert variables into strings using template literals:

actionButton("show1", class = "act_button", 
  list(
    span(id = "m1", , "Model 1"), 
    span(, Sys.time())
  ),
  onclick = `Shiny.setInputValue(
    'btnid', document.getElementById('${dynamicId}').textContent);
  `)
  • Related