Search code examples
rshinyshinywidgets

How to use callbackJS in shinyWidgets?


I used to use in Shinyalert, but because there are some bugs I try to use in shinyWidgets (ask_confirmation). In Shinyalert I used callbackJS to know if the user click on OK or on Cancel, but it is not working in ask_confirmation.

library(shiny)
library(shinyWidgets)

ui <- fluidPage(
)

server <- function(input, output, session) {
  ask_confirmation(
    "form1",
    title = " ",
    type = "question",
    btn_labels = c("Cancel", "OK"),
    allowEscapeKey = TRUE,
    closeOnClickOutside = TRUE,
    html = TRUE,
    #######################
    #this one is not woking
    callbackJS =      "  
    function(x) {
      if (x !== false) {
      alert('t');
      }
    else{
    alert('ttt');
    }
}
    
    ",
    ######################
    text =  
      div(HTML("
    
<form style = ' display:flex; flex-direction: row; justify-content: center; align-items: center' action=''>
<div style='border: 5px  black;'>
<input type='text'name='add_nosha_tohen' autocomplete='off' id='add_nosha_tohen' value=''   dir='rtl' style='border-color: black; font-size: 12px;height: 45px; width: 400px; display: block;'/></input>
</div>
</form>
"
      ))
  )
}

shinyApp(ui, server)

Any idea how can I fix it?


Solution

  • There is no callbackJS argument in ask_confirmation. To do a callback, and run JS code, you can do:

    library(shiny)
    library(shinyWidgets)
    library(shinyjs)
    ui <- fluidPage(
        useShinyjs()
    )
    
    server <- function(input, output, session) {
        ask_confirmation(
            "form1",
            title = " ",
            type = "question",
            btn_labels = c("Cancel", "OK"),
            allowEscapeKey = TRUE,
            closeOnClickOutside = TRUE,
            html = TRUE,
    ######################
    text =  
        div(HTML("
    <form style = ' display:flex; flex-direction: row; justify-content: center; align-items: center' action=''>
    <div style='border: 5px  black;'>
    <input type='text'name='add_nosha_tohen' autocomplete='off' id='add_nosha_tohen' value=''   dir='rtl' style='border-color: black; font-size: 12px;height: 45px; width: 400px; display: block;'/></input>
    </div>
    </form>
    "
        ))
        )
        
        observeEvent(input$form1, {
            if(is.null(input$form1)) runjs("alert('NULL');")
            else if (input$form1) runjs("alert('true');")
            else runjs("alert('false');")
        }, ignoreNULL = TRUE)
    }
    
    shinyApp(ui, server)
    

    enter image description here