I developed an online shiny application which contains a textInput()
widget to input a location name and, accordingly, redirect the user on that location on a map (exploiting the Google API's features through the geocode
package).
I would like to change my current textInput()
widget with another one that has a "X" button incorporated in it to automatically delete the text that the user inserts. Please check this image to see an example of it (the "X" button is marked in red).
Do you know if it's possible to do inside a shiny app? Thanks a lot.
Try this:
library(shiny)
clearableTextInput <- function(inputId, label, value = ""){
el <- tags$div(
tags$label(label, `for` = inputId),
tags$span(
class = "text-input-clearable",
tags$input(id = inputId, type = "text", value = value),
tags$span(title = "Clear", HTML("×"))
)
)
js <- sprintf('
var textInput = document.getElementById("%s");
var clearBtn = textInput.nextElementSibling;
textInput.onkeyup = function() {
clearBtn.style.visibility = (this.value.length) ? "visible" : "hidden";
};
clearBtn.onclick = function() {
this.style.visibility = "hidden";
textInput.value = "";
Shiny.setInputValue("%s", "");
};
', inputId, inputId)
tagList(el, singleton(tags$script(HTML(js))))
}
CSS <- "
.text-input-clearable {
border:1px solid;
padding:1px 6px 1px 1px;
display:inline-block;
}
.text-input-clearable input {
border:none;
background:none;
outline:none;
padding:0 0;
margin:0 0;
font:inherit;
}
.text-input-clearable span {
cursor:pointer;
color:blue;
font-weight:bold;
visibility:hidden;
}
"
ui <- fluidPage(
tags$head(
tags$style(HTML(CSS))
),
br(),
clearableTextInput("txt", "Label"),
br(),
verbatimTextOutput("txt")
)
server <- function(input, output, session){
output[["txt"]] <- renderPrint({
input[["txt"]]
})
}
shinyApp(ui, server)