Gleaming R: Warning prompt or modal box input: invalid

In the process of developing a basic application, I am seeking to implement a pop-up notification for invalid inputs. By referencing the suggestion provided in #1656, I have come up with an example that introduces a visually appealing background color when dealing with invalid inputs (especially considering my 300 variables):

library(shiny)

ui <- fluidPage(
  tags$style(HTML("
    input:invalid {
  background-color: #FFCCCC;
                  }")),

  numericInput("myValue", "My Variable", min = 0, max = 1, value = 0.5),
  numericInput("myValue2", "My Variable2", min = 0, max = 3, step = 0.5, value = 0.5),
  textOutput("text"),
  textOutput("text2")
)

server <- function(input, output) {
  output$text <- renderText(input$myValue)
  output$text2 <- renderText(input$myValue2)
}

shinyApp(ui, server)

Although the

tags$style("input:invalid{ ... }")),
method is effective, I am interested in implementing a bootstrap alert instead of solely modifying the background color.

Essentially, I would like to incorporate the following div class within the input:invalid{} section (considering the extensive list of 300 variables to validate):

<div class="alert alert-danger">
  <strong>Danger!</strong> Indicates a dangerous or potentially negative action.
</div>

I would greatly appreciate any input or recommendations on how to achieve this desired functionality.

Answer №1

Note: Below is an updated version of your example featuring alerts for invalid entries based on this solution. These alerts can be triggered when the user either clicks out of the input box (blur) or finishes typing (keyup). Using keyup might be more appropriate for this scenario.

library(shiny)

alert <- '$(document).ready(function() {
            $(function () {
             $("input").keyup(function () {
                 if ($(this).is(":invalid")) {
                     alert(\'Invalid entry!\');
                     }
                 });
             });
         })'

ui <- fluidPage(
    tags$head(tags$script(HTML(alert))),
    tags$style(HTML("
                    input:invalid {
                    background-color: #FFCCCC;
                    }")),
    numericInput("myValue", "My Variable", min = 0, max = 1, value = 0.5),
    numericInput("myValue2", "My Variable2", min = 0, max = 3, step = 0.5, value = 0.5),
    textOutput("text"),
    textOutput("text2")
    )

server <- function(input, output) {
    output$text <- renderText(input$myValue)
    output$text2 <- renderText(input$myValue2)

}

shinyApp(ui, server)

Explore several options below:

  1. shiny: Use modalDialog or showNotification

  2. shinyjs: Check out alert

  3. shinyBS: Utilize bsAlert, and test with bsExamples("Alerts")


The following showcases your sample app incorporating these functions. Observe that both shinyjs and shinyBS necessitate statements in both the ui and server sections, whereas modalDialog only demands additions in the server section. Note that to use shinyJS alongside shinyBS, you must include session within the server function.

library(shiny)
library(shinyjs)
library(shinyBS)

ui <- fluidPage(
    tags$style(HTML("
                    input:invalid {
                    background-color: #FFCCCC;
                    }")),
    #### Initialize shinyjs ####
    useShinyjs(),

    ### Implementing shinyBS ###
    bsAlert("alert"),

    numericInput("myValue", "My Variable", min = 0, max = 1, value = 0.5),
    numericInput("myValue2", "My Variable2", min = 0, max = 3, step = 0.5, value = 0.5),
    textOutput("text"),
    textOutput("text2")
    )

server <- function(session, input, output) {
    output$text <- renderText({
        ### Working with shinyBS ###
        if(!(is.na(input$myValue)) && (input$myValue > 1 | input$myValue < 0)) {
            createAlert(session, "alert", "myValueAlert", title = "shinyBS: Invalid input",
                        content = "'My Variable' should fall between 0 and 1", style = "danger")
        } else {
            closeAlert(session, "myValueAlert")
            return(input$myValue)
        }
        })
    output$text2 <- renderText(input$myValue2)

    ### modalDialog Setup###
     observeEvent(input$myValue, {
         if(!is.na(input$myValue) && (input$myValue > 1 | input$myValue < 0)) {
             showModal(modalDialog(
                 title = "modalDialog: Invalid input",
                 "'My Variable' should fall between 0 and 1"
             ))   
         }
     })

    ### Integrating shinyjs Alert###
    observeEvent(input$myValue, {
        if(!(is.na(input$myValue)) && (input$myValue > 1 | input$myValue < 0)) {
            alert("shinyJS: 'My Variable' should be between 0 and 1")
        }
    })

}

shinyApp(ui, server)

Answer №2

If you want to target all inputs that start with "myValue," you can use the following selector:

$('input[id^="myValue"]')

Initially, I attempted the following code:

$(document).ready(function(){
  $('input[id^="myValue"]').on("invalid", function(){alert("invalid");});
})

However, this code didn't work for some reason.

For my second approach, I used the Shiny library to achieve the desired functionality:

library(shiny)
js <- '$(document).ready(function(){
$("input[id^=\\\"myValue\\\"]").on("keyup", function(){
  if($(this)[0].checkValidity()){
    $(this).tooltip("destroy");
  }else{
    $(this).tooltip({title:"invalid"});
  }
})
})
'
ui <- fluidPage(
  tags$head(
    tags$script(js)
  ),
  numericInput("myValue", "My Variable", min = 0, max = 1, value = 0.5),
  numericInput("myValue2", "My Variable2", min = 0, max = 3, step = 0.5, value = 0.5),
  textOutput("text"),
  textOutput("text2")
  )

server <- function(input, output) {
  output$text <- renderText(input$myValue)
  output$text2 <- renderText(input$myValue2)
}

shinyApp(ui, server)

Although this method achieved the desired outcome, I encountered errors in the console when the input was valid. The cause of these errors is currently unknown to me.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Steps for splitting a numbered list and adding an image above each item:

I have a challenge I'm trying to tackle with my list: My goal is to create a long, numbered list that is divided into different sections I also want to include an image within each list item and have it display above the numbered title of the sectio ...

Limit selection choices in select element

Similar Question: Prevent select dropdown from opening in FireFox and Opera In my HTML file, I have a select tag that I want to use to open my own table when clicked. However, the window of the Select tag also opens, which is not desirable. Is there a ...

The resize function fails to trigger when it is required

Struggling to get this code working properly. If the window width is greater than 800, I want 6 images with a red background. If the window width is less than 800, I want 4 images with a blue background. I need this functionality to work both on r ...

Having difficulty compiling Bootstrap css with grunt

After struggling for two days and finding numerous online tutorials, I still require assistance. My goal is to add a namespace to Bootstrap so that I can use it in Salesforce without conflicting with Salesforce's stylesheet. I plan on wrapping the boo ...

Safari experiences a decrease in speed when multiple checkbox elements are present

While using Safari, I have encountered a problem. The performance of interacting with a text input is significantly affected when there are numerous type="checkbox" elements on the page. This issue appears to be more pronounced in Safari compared to Chrom ...

Interacting with jQuery UI Droppable by setting acceptance criteria before submitting a form

My goal is to create a draggable item that can be dropped onto a specific zone. The challenge I'm facing is in displaying a form for inputting information and storing it in a database. If the input is successfully stored, the drop action will be succe ...

Conceal the element if the output of express is void

I am currently developing an app using nodejs and express. I am retrieving JSON data from an endpoint and displaying it on the page based on the values received. The issue I am facing is that if I receive a null or undefined value from the JSON data, how ...

Ways to eliminate dates from the text of listed items

Before finalizing their registration, users on our site are shown a review page. This panel displays all the items they have selected, creating a unique and variable list for each individual. However, each item in the list starts with a distracting date/ti ...

Universal CSS styling for scrollbar design across platforms

I'm feeling extremely frustrated right now because I can't seem to create a basic scroll bar with a specific color and thickness that will display properly on various web browsers and smartphones. Are there any resources available to help me fig ...

Stretch element to reach the edge of the container

I need help with positioning an input and a textarea inside a container that has a height of 52.5vh. I want the textarea to start right below the input and expand all the way to the end of the container. How can I achieve this layout? Both elements should ...

How to show a picture stored in a MySQL database using PHP

I have been experimenting with displaying images uploaded to the database using a simple insert form. So far, I have managed to retrieve the image name in the "data-file". However, I am curious about how I can easily display the actual image in the same lo ...

Turn off the background when the automatic popup box appears

I have implemented a popup box that automatically appears after 5 seconds when the site is loaded. However, if I click outside of the popup box, it closes. I want to disable the background when the popup box is displayed. If I remove the two lines of code ...

What could be preventing the onclick event from functioning properly in JavaScript?

After creating a basic JavaScript code to practice Event handling, I encountered an issue where the function hello() does not execute when clicking on the "Click" button. What could be causing this problem? html file: <!DOCTYPE html> <html> ...

Save mathematical equations written in HTML text boxes to a MySQL database

How can I display mathematical formulas in a text input and store them in a database? I need to be able to display formulas like the ones shown in the image at this link: Currently, when I copy any formula into the text box, it gets converted to normal t ...

What could be causing my CSS/Layout to alter once AJAX/JavaScript has been executed?

When the user clicks, an AJAX call is made to retrieve data from a third-party API. The frontend/layout renders correctly before this action; however, after the data is fetched and displayed in the frontend, the layout changes. Upon debugging multiple tim ...

Adding a Sequence of Class Names to <li> Elements with JavaScript

How can you easily generate sequential class names in a for loop? ...

if jade is being inconsistent

I am currently using expressjs in my app and have the following setup: app.get('/profile',index.profile); app.get('/',index.home); Within layout.jade, I have the following code: ... if typeof(username)!=='undefined' ...

Is there a way to eliminate the space between the gray background and the right edge of the browser window?

body{ font-family:'Montserrat'; } .content{ background-color:#d9d9d9; } p.dates{ display:inline-block; font-weight:800; margin-right:20px; width:120px; text-align:center; margin-top:0; margin-bott ...

Attempting to output numerical values using Jquery, however instead of integer values, I am met with [Object object]

I am struggling to figure out how to display the value contained in my object after attempting to create a Calendar using Jquery. I attempted to use JSON.toString() on my table data, but it didn't solve the issue. Perhaps I am not placing the toString ...

Tips for creating animations with JavaScript on a webpage

I created a navigation bar for practice and attempted to show or hide its content only when its title is clicked. I successfully toggled a hidden class on and off, but I also wanted it to transition and slide down instead of just appearing suddenly. Unfort ...