Incorporating javascript in shiny

I pretty sure that my end goal here can be achieved here with just shiny functions. But I need to achieve this by using javascript since I am learning it.

library(shiny)

ui <- fluidPage(
  tags$head(tags$style(".shiny-output-error { visibility: hidden; }")),
  verbatimTextOutput("ca"),
  
  tags$body(tags$button(id="alert", type="button","Calling car properties")),
  # selectInput("df","select",choices = c("f","Sdf")),
  
  tags$script('
  function car(seats, engine, theradio) {
            this.seats = seats;
            this.engine = engine;
            this.theradio = theradio;
        }
document.getElementById("alert").onclick = function event(){
debugger
this.seats=seats;
this.engine=engine;
this.theradio=theradio;
var work_car= new car("cloth", "input" ,"Tape Deck");
var fun_car= new car("leather","V-11","CD Player");
var engine_type= work_car.engine;
var seat_type= fun_car.seats;
var radio_type= fun_car.theradio;
Shiny.setInputValue("car_ob", radio_type);
};
')
  
)

server <- function(input, output, session) {
  
  output$ca = renderPrint({
    input$car_ob
  })
  # document.write("I want a car with "+seat_type+" seats.<br />");
  # document.write("It also needs a "+engine_type+" engine.<br />");
  # document.write("Oh, and I would like a "+radio_type+" also.");

  
}

shinyApp(ui, server)

My end goal is here is to have "V-6" printed on shiny page post clicking the button

Let me explain what I am trying here

  1. I have created a car object with 3 parameter/properties.
  2. I have created an instance with new keyword and calling work_car= new car("cloth","V-6","Tape Deck")
  3. At last I am trying to return work_car.engine that is "V-6

Hi,

I don't know much about javascript, but here is one way it does work for me after trimming some of the code:

library(shiny)

ui <- fluidPage(
  tags$head(tags$style(".shiny-output-error { visibility: hidden; }")),
  verbatimTextOutput("ca"),
  
  tags$body(tags$button(id="alert", type="button","Calling car properties")),
  # selectInput("df","select",choices = c("f","Sdf")),
  
  tags$script('
  function car(seats, engine, theradio) {
            this.seats = seats;
            this.engine = engine;
            this.theradio = theradio;
        }
  document.getElementById("alert").onclick = function event(){
  
    var work_car= new car("cloth", "V-6" ,"Tape Deck");
    var fun_car= new car("leather","V-11","CD Player");
  
    Shiny.setInputValue("car_ob", work_car.engine);
  };
')
  
)

server <- function(input, output, session) {
  
  output$ca = renderPrint({
    input$car_ob
  })

  }

shinyApp(ui, server)

Thanks it worked for me. Thanks for the help

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.