0

Because the checkboxGroup included in Shiny doesn't exactly fit my needs, I am rebuilding the checkboxGroup function. I am looking for a way to include an element named checked in the arguments passed to tags$input(...) depending on a boolean variable.

I wish that the following code worked as desired, but I understand why it doesn't and shouldn't. Is there any similarly concise syntax I can use to achieve the desired result?

f <- function(selected = TRUE) {
  tags$input(
    type = 'checkbox',
    if(selected) checked = "checked",
    "Checkbox Content"
  )
}

f()
# actual result:
# <input type="checkbox">
#   checked
#   Checkbox Content
# </input>

# desired result:
# <input type="checkbox" checked = "checked">
#   Checkbox Content
# </input>
ctesta01
  • 909
  • 8
  • 19
  • I don't really understand but can't you use `renderUI` ? – Stéphane Laurent Apr 02 '18 at 14:55
  • 1
    Othewise, anyway, you should do `tags$input(type = 'checkbox', checked = if(selected) "checked", "Checkbox Content")` – Stéphane Laurent Apr 02 '18 at 14:57
  • The dilemma is if checked is included as a named parameter at all, it will cause the checkbox to be checked. See https://stackoverflow.com/questions/12700626/what-is-the-proper-way-to-check-and-uncheck-a-checkbox-in-html5 – ctesta01 Apr 02 '18 at 15:18

1 Answers1

1

It's not super easy to conditionally add parameters to a function call, but you can do something like this

f <- function(selected = TRUE) {
  tag <- tags$input(
    type = 'checkbox',
    "Checkbox Content"
  )
  if (selected) tag <- tagAppendAttributes(tag, selected=TRUE)
  tag
}

f(TRUE)
# <input type="checkbox" selected="TRUE">Checkbox Content</input>
f(FALSE)
# <input type="checkbox">Checkbox Content</input>
MrFlick
  • 195,160
  • 17
  • 277
  • 295
  • Thanks. This is what I was thinking. I'll accept this as the answer if nobody can provide a more "inline" or more simple/concise answer. – ctesta01 Apr 02 '18 at 15:32
  • 1
    @ctesta01 The other way I can think of is to build all your arguments into a list and call the function with `do.call`. MrFlick's solution is more concise. – Gregor Thomas Apr 02 '18 at 15:35