如何禁用Shiny中numericInput组件的错误提示消息?
Shiny numericInput 错误悬浮提示处理方案
问题原因
该提示是HTML原生数字输入框的默认校验逻辑:当你将step设为1、初始值设为带小数的数值时,浏览器会默认所有合法值必须为「初始值 + N倍步长」,因此弹出仅xx结尾数值合法的误导性提示。
解决方案
以上两种方案均基于Shiny原生功能实现,无需安装第三方扩展包,且都会保留点击上下箭头每次加减1的步长设置,同时支持输入任意数值。
方案1:完全禁用提示
直接清空默认悬浮提示并禁用原生校验:
library(shiny) ui <- fluidPage( # 给numericInput追加属性禁用校验 tagAppendAttributes( numericInput( inputId = "test_num", label = "数值输入", value = 53.66, step = 1 ), oninvalid = "return false;", title = "" ) ) server <- function(input, output) {} shinyApp(ui, server)
方案2:自定义提示内容
如果需要保留提示功能,可自行修改悬浮提示和校验报错内容:
library(shiny) ui <- fluidPage( numericInput( inputId = "test_num", label = "数值输入", value = 53.66, step = 1 ), # 注入JS修改默认提示 tags$script(HTML(" const numInput = document.getElementById('test_num'); // 自定义悬浮提示 numInput.title = '上下箭头调整步长为1,也可直接输入任意数值'; // 自定义校验报错 numInput.oninvalid = () => numInput.setCustomValidity('请输入合法数值'); numInput.oninput = () => numInput.setCustomValidity(''); ")) ) server <- function(input, output) {} shinyApp(ui, server)
内容的提问来源于stack exchange,提问作者Mateus Figueiredo
相关产品推荐
相关产品推荐

